blob: 864aaea76f2d261eac266e67e29171b6f9cf6dcf [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>
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -080025#include <gmock/gmock.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080026#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100027#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080028#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080029#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031#include <cinttypes>
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080032#include <compare>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070033#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080034#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080035#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080036
Garfield Tan1c7bc862020-01-28 13:24:04 -080037using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050038using android::gui::FocusRequest;
39using android::gui::TouchOcclusionMode;
40using android::gui::WindowInfo;
41using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080042using android::os::InputEventInjectionResult;
43using android::os::InputEventInjectionSync;
Garfield Tan1c7bc862020-01-28 13:24:04 -080044
Garfield Tane84e6f92019-08-29 17:28:41 -070045namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080046
Dominik Laskowski2f01d772022-03-23 16:01:29 -070047using namespace ftl::flag_operators;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -080048using testing::AllOf;
Dominik Laskowski2f01d772022-03-23 16:01:29 -070049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050// An arbitrary time value.
Prabir Pradhan5735a322022-04-11 17:23:34 +000051static constexpr nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
53// An arbitrary device id.
Prabir Pradhan5735a322022-04-11 17:23:34 +000054static constexpr int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080055
Jeff Brownf086ddb2014-02-11 14:28:48 -080056// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000057static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
58static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080059
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080060static constexpr int32_t ACTION_OUTSIDE = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080061static constexpr int32_t POINTER_1_DOWN =
62 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000063static constexpr int32_t POINTER_2_DOWN =
64 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000065static constexpr int32_t POINTER_3_DOWN =
66 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Arthur Hungc539dbb2022-12-08 07:45:36 +000067static constexpr int32_t POINTER_0_UP =
68 AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080069static constexpr int32_t POINTER_1_UP =
70 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
71
Antonio Kantek15beb512022-06-13 22:35:41 +000072// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000073static constexpr int32_t WINDOW_PID = 999;
74static constexpr int32_t WINDOW_UID = 1001;
75
Antonio Kantek15beb512022-06-13 22:35:41 +000076// The default pid and uid for the windows created on the secondary display by the test.
77static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
78static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
79
Prabir Pradhan5735a322022-04-11 17:23:34 +000080// The default policy flags to use for event injection by tests.
81static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000083// An arbitrary pid of the gesture monitor window
84static constexpr int32_t MONITOR_PID = 2001;
85
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080086static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
87
Arthur Hungc539dbb2022-12-08 07:45:36 +000088static constexpr int expectedWallpaperFlags =
89 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
90
chaviwd1c23182019-12-20 18:44:56 -080091struct PointF {
92 float x;
93 float y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080094 auto operator<=>(const PointF&) const = default;
chaviwd1c23182019-12-20 18:44:56 -080095};
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Gang Wang342c9272020-01-13 13:15:04 -050097/**
98 * Return a DOWN key event with KEYCODE_A.
99 */
100static KeyEvent getTestKeyEvent() {
101 KeyEvent event;
102
Garfield Tanfbe732e2020-01-24 11:26:14 -0800103 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
104 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
105 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -0500106 return event;
107}
108
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000109static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
110 ASSERT_EQ(expectedAction, receivedAction)
111 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
112 << MotionEvent::actionToString(receivedAction);
113}
114
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800115MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
116 bool matches = action == arg.getAction();
117 if (!matches) {
118 *result_listener << "expected action " << MotionEvent::actionToString(action)
119 << ", but got " << MotionEvent::actionToString(arg.getAction());
120 }
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800121 if (action == AMOTION_EVENT_ACTION_DOWN) {
122 if (!matches) {
123 *result_listener << "; ";
124 }
125 *result_listener << "downTime should match eventTime for ACTION_DOWN events";
126 matches &= arg.getDownTime() == arg.getEventTime();
127 }
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800128 if (action == AMOTION_EVENT_ACTION_CANCEL) {
129 if (!matches) {
130 *result_listener << "; ";
131 }
132 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
133 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
134 }
135 return matches;
136}
137
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800138MATCHER_P(WithDownTime, downTime, "InputEvent with specified downTime") {
139 return arg.getDownTime() == downTime;
140}
141
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800142MATCHER_P(WithSource, source, "InputEvent with specified source") {
143 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
144 << inputEventSourceToString(arg.getSource());
145 return arg.getSource() == source;
146}
147
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800148MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
149 if (arg.getPointerCount() != 1) {
150 *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
151 return false;
152 }
153 return arg.getX(0 /*pointerIndex*/) == x && arg.getY(0 /*pointerIndex*/) == y;
154}
155
156MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
157 // Build a map for the received pointers, by pointer id
158 std::map<int32_t /*pointerId*/, PointF> actualPointers;
159 for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
160 const int32_t pointerId = arg.getPointerId(pointerIndex);
161 actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
162 }
163 return pointers == actualPointers;
164}
165
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166// --- FakeInputDispatcherPolicy ---
167
168class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
169 InputDispatcherConfiguration mConfig;
170
Prabir Pradhanedd96402022-02-15 01:46:16 -0800171 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
172
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000174 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175
176public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000177 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800178
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800179 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700180 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
181 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
182 EXPECT_EQ(event.getDisplayId(), args.displayId);
183
184 const auto& keyEvent = static_cast<const KeyEvent&>(event);
185 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
186 EXPECT_EQ(keyEvent.getAction(), args.action);
187 });
Jackal Guof9696682018-10-05 12:23:23 +0800188 }
189
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700190 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
191 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
192 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
193 EXPECT_EQ(event.getDisplayId(), args.displayId);
194
195 const auto& motionEvent = static_cast<const MotionEvent&>(event);
196 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
197 EXPECT_EQ(motionEvent.getAction(), args.action);
198 EXPECT_EQ(motionEvent.getX(0), point.x);
199 EXPECT_EQ(motionEvent.getY(0), point.y);
200 EXPECT_EQ(motionEvent.getRawX(0), point.x);
201 EXPECT_EQ(motionEvent.getRawY(0), point.y);
202 });
Jackal Guof9696682018-10-05 12:23:23 +0800203 }
204
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700205 void assertFilterInputEventWasNotCalled() {
206 std::scoped_lock lock(mLock);
207 ASSERT_EQ(nullptr, mFilteredEvent);
208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800210 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700211 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800212 ASSERT_TRUE(mConfigurationChangedTime)
213 << "Timed out waiting for configuration changed call";
214 ASSERT_EQ(*mConfigurationChangedTime, when);
215 mConfigurationChangedTime = std::nullopt;
216 }
217
218 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700219 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800220 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800221 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800222 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
223 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
224 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
225 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
226 mLastNotifySwitch = std::nullopt;
227 }
228
chaviwfd6d3512019-03-25 13:23:49 -0700229 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700230 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800231 ASSERT_EQ(touchedToken, mOnPointerDownToken);
232 mOnPointerDownToken.clear();
233 }
234
235 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700236 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800237 ASSERT_TRUE(mOnPointerDownToken == nullptr)
238 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700239 }
240
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700241 // This function must be called soon after the expected ANR timer starts,
242 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500243 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700244 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500245 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800246 std::unique_lock lock(mLock);
247 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500248 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800249 ASSERT_NO_FATAL_FAILURE(
250 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500251 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700252 }
253
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000254 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800255 const sp<WindowInfoHandle>& window) {
256 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
257 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
258 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500259 }
260
Prabir Pradhanedd96402022-02-15 01:46:16 -0800261 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
262 const sp<IBinder>& expectedToken,
263 int32_t expectedPid) {
264 std::unique_lock lock(mLock);
265 android::base::ScopedLockAssertion assumeLocked(mLock);
266 AnrResult result;
267 ASSERT_NO_FATAL_FAILURE(result =
268 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
269 const auto& [token, pid] = result;
270 ASSERT_EQ(expectedToken, token);
271 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500272 }
273
Prabir Pradhanedd96402022-02-15 01:46:16 -0800274 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000275 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500276 std::unique_lock lock(mLock);
277 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800278 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
279 const auto& [token, _] = result;
280 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000281 }
282
Prabir Pradhanedd96402022-02-15 01:46:16 -0800283 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
284 int32_t expectedPid) {
285 std::unique_lock lock(mLock);
286 android::base::ScopedLockAssertion assumeLocked(mLock);
287 AnrResult result;
288 ASSERT_NO_FATAL_FAILURE(
289 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
290 const auto& [token, pid] = result;
291 ASSERT_EQ(expectedToken, token);
292 ASSERT_EQ(expectedPid, pid);
293 }
294
295 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000296 sp<IBinder> getResponsiveWindowToken() {
297 std::unique_lock lock(mLock);
298 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800299 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
300 const auto& [token, _] = result;
301 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700302 }
303
304 void assertNotifyAnrWasNotCalled() {
305 std::scoped_lock lock(mLock);
306 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800307 ASSERT_TRUE(mAnrWindows.empty());
308 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500309 << "ANR was not called, but please also consume the 'connection is responsive' "
310 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700311 }
312
Garfield Tan1c7bc862020-01-28 13:24:04 -0800313 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
314 mConfig.keyRepeatTimeout = timeout;
315 mConfig.keyRepeatDelay = delay;
316 }
317
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000318 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800319 std::unique_lock lock(mLock);
320 base::ScopedLockAssertion assumeLocked(mLock);
321
322 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
323 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000324 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800325 enabled;
326 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000327 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
328 << ") to be called.";
329 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800330 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000331 auto request = *mPointerCaptureRequest;
332 mPointerCaptureRequest.reset();
333 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800334 }
335
336 void assertSetPointerCaptureNotCalled() {
337 std::unique_lock lock(mLock);
338 base::ScopedLockAssertion assumeLocked(mLock);
339
340 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000341 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800342 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000343 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800344 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000345 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800346 }
347
arthurhungf452d0b2021-01-06 00:19:52 +0800348 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
349 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800350 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800351 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800352 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800353 }
354
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800355 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
356 std::unique_lock lock(mLock);
357 base::ScopedLockAssertion assumeLocked(mLock);
358 std::optional<sp<IBinder>> receivedToken =
359 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
360 mNotifyInputChannelBroken);
361 ASSERT_TRUE(receivedToken.has_value());
362 ASSERT_EQ(token, *receivedToken);
363 }
364
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800365 /**
366 * Set policy timeout. A value of zero means next key will not be intercepted.
367 */
368 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
369 mInterceptKeyTimeout = timeout;
370 }
371
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700373 std::mutex mLock;
374 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
375 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
376 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
377 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800378
Prabir Pradhan99987712020-11-10 18:43:05 -0800379 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000380
381 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800382
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700383 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700384 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800385 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
386 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700387 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800388 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
389 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700390
arthurhungf452d0b2021-01-06 00:19:52 +0800391 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800392 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800393
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800394 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
395
Prabir Pradhanedd96402022-02-15 01:46:16 -0800396 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
397 // for a specific container to become non-empty. When the container is non-empty, return the
398 // first entry from the container and erase it.
399 template <class T>
400 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
401 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
402 // If there is an ANR, Dispatcher won't be idle because there are still events
403 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
404 // before checking if ANR was called.
405 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
406 // to provide it some time to act. 100ms seems reasonable.
407 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
408 const std::chrono::time_point start = std::chrono::steady_clock::now();
409 std::optional<T> token =
410 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
411 if (!token.has_value()) {
412 ADD_FAILURE() << "Did not receive the ANR callback";
413 return {};
414 }
415
416 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
417 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
418 // the dispatcher started counting before this function was called
419 if (std::chrono::abs(timeout - waited) > 100ms) {
420 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
421 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
422 << "ms, but waited "
423 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
424 << "ms instead";
425 }
426 return *token;
427 }
428
429 template <class T>
430 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
431 std::queue<T>& storage,
432 std::unique_lock<std::mutex>& lock,
433 std::condition_variable& condition)
434 REQUIRES(mLock) {
435 condition.wait_for(lock, timeout,
436 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
437 if (storage.empty()) {
438 ADD_FAILURE() << "Did not receive the expected callback";
439 return std::nullopt;
440 }
441 T item = storage.front();
442 storage.pop();
443 return std::make_optional(item);
444 }
445
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600446 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700447 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800448 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 }
450
Prabir Pradhanedd96402022-02-15 01:46:16 -0800451 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
452 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700453 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800454 ASSERT_TRUE(pid.has_value());
455 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700456 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500457 }
458
Prabir Pradhanedd96402022-02-15 01:46:16 -0800459 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
460 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500461 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800462 ASSERT_TRUE(pid.has_value());
463 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500464 mNotifyAnr.notify_all();
465 }
466
467 void notifyNoFocusedWindowAnr(
468 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
469 std::scoped_lock lock(mLock);
470 mAnrApplications.push(applicationHandle);
471 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 }
473
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800474 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
475 std::scoped_lock lock(mLock);
476 mBrokenInputChannels.push(connectionToken);
477 mNotifyInputChannelBroken.notify_all();
478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600480 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700481
Chris Yef59a2f42020-10-16 12:55:26 -0700482 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
483 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
484 const std::vector<float>& values) override {}
485
486 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
487 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000488
Chris Yefb552902021-02-03 17:18:37 -0800489 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
490
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600491 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 *outConfig = mConfig;
493 }
494
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600495 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700496 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800497 switch (inputEvent->getType()) {
498 case AINPUT_EVENT_TYPE_KEY: {
499 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800500 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800501 break;
502 }
503
504 case AINPUT_EVENT_TYPE_MOTION: {
505 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800506 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800507 break;
508 }
509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 return true;
511 }
512
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800513 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
514 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
515 // Clear intercept state when we handled the event.
516 mInterceptKeyTimeout = 0ms;
517 }
518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600520 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600522 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800523 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
524 // Clear intercept state so we could dispatch the event in next wake.
525 mInterceptKeyTimeout = 0ms;
526 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 }
528
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600529 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 return false;
531 }
532
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600533 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
534 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700535 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800536 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
537 * essentially a passthrough for notifySwitch.
538 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800539 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 }
541
Sean Stoutb4e0a592021-02-23 07:34:53 -0800542 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600544 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700545 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700546 mOnPointerDownToken = newToken;
547 }
548
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000549 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800550 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000551 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800552 mPointerCaptureChangedCondition.notify_all();
553 }
554
arthurhungf452d0b2021-01-06 00:19:52 +0800555 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
556 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800557 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800558 mDropTargetWindowToken = token;
559 }
560
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700561 void assertFilterInputEventWasCalledInternal(
562 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700563 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800564 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700565 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800566 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568};
569
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570// --- InputDispatcherTest ---
571
572class InputDispatcherTest : public testing::Test {
573protected:
574 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700575 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000577 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700578 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800579 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800580 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000581 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700582 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 }
584
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000585 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700586 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700588 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700590
591 /**
592 * Used for debugging when writing the test
593 */
594 void dumpDispatcherState() {
595 std::string dump;
596 mDispatcher->dump(dump);
597 std::stringstream ss(dump);
598 std::string to;
599
600 while (std::getline(ss, to, '\n')) {
601 ALOGE("%s", to.c_str());
602 }
603 }
Vishnu Nair958da932020-08-21 17:12:37 -0700604
chaviw3277faf2021-05-19 16:45:23 -0500605 void setFocusedWindow(const sp<WindowInfoHandle>& window,
606 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700607 FocusRequest request;
608 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000609 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700610 if (focusedWindow) {
611 request.focusedToken = focusedWindow->getToken();
612 }
613 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
614 request.displayId = window->getInfo()->displayId;
615 mDispatcher->setFocusedWindow(request);
616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617};
618
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
620 KeyEvent event;
621
622 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800623 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
624 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600625 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
626 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800627 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000628 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
629 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 << "Should reject key events with undefined action.";
631
632 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800633 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
634 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600635 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000637 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
638 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 << "Should reject key events with ACTION_MULTIPLE.";
640}
641
642TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
643 MotionEvent event;
644 PointerProperties pointerProperties[MAX_POINTERS + 1];
645 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800646 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 pointerProperties[i].clear();
648 pointerProperties[i].id = i;
649 pointerCoords[i].clear();
650 }
651
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800652 // Some constants commonly used below
653 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
654 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
655 constexpr int32_t metaState = AMETA_NONE;
656 constexpr MotionClassification classification = MotionClassification::NONE;
657
chaviw9eaa22c2020-07-01 16:21:27 -0700658 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800660 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700661 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
662 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700663 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
664 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700665 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000667 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
668 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 << "Should reject motion events with undefined action.";
670
671 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800672 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800673 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
674 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
675 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
676 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500677 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800678 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000679 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
680 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 << "Should reject motion events with pointer down index too large.";
682
Garfield Tanfbe732e2020-01-24 11:26:14 -0800683 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700684 AMOTION_EVENT_ACTION_POINTER_DOWN |
685 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700686 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
687 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700688 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500689 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800690 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000691 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
692 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 << "Should reject motion events with pointer down index too small.";
694
695 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800696 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800697 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
698 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
699 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
700 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500701 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800702 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000703 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
704 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 << "Should reject motion events with pointer up index too large.";
706
Garfield Tanfbe732e2020-01-24 11:26:14 -0800707 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700708 AMOTION_EVENT_ACTION_POINTER_UP |
709 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700710 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
711 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700712 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500713 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800714 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000715 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
716 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 << "Should reject motion events with pointer up index too small.";
718
719 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800720 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
721 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700722 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700723 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
724 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700725 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800726 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000727 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
728 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 << "Should reject motion events with 0 pointers.";
730
Garfield Tanfbe732e2020-01-24 11:26:14 -0800731 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
732 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700733 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700734 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
735 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700736 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000738 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
739 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 << "Should reject motion events with more than MAX_POINTERS pointers.";
741
742 // Rejects motion events with invalid pointer ids.
743 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800744 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
745 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700746 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700747 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
748 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700749 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800750 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000751 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
752 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 << "Should reject motion events with pointer ids less than 0.";
754
755 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800756 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
757 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700758 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700759 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
760 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700761 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800762 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000763 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
764 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
766
767 // Rejects motion events with duplicate pointer ids.
768 pointerProperties[0].id = 1;
769 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800770 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
771 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700772 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700773 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
774 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700775 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800776 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000777 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
778 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 << "Should reject motion events with duplicate pointer ids.";
780}
781
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800782/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
783
784TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
785 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800786 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800787 mDispatcher->notifyConfigurationChanged(&args);
788 ASSERT_TRUE(mDispatcher->waitForIdle());
789
790 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
791}
792
793TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800794 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
795 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800796 mDispatcher->notifySwitch(&args);
797
798 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
799 args.policyFlags |= POLICY_FLAG_TRUSTED;
800 mFakePolicy->assertNotifySwitchWasCalled(args);
801}
802
Arthur Hungb92218b2018-08-14 12:00:21 +0800803// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700804static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700805// Default input dispatching timeout if there is no focused application or paused window
806// from which to determine an appropriate dispatching timeout.
807static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
808 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
809 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800810
811class FakeApplicationHandle : public InputApplicationHandle {
812public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700813 FakeApplicationHandle() {
814 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700815 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500816 mInfo.dispatchingTimeoutMillis =
817 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700818 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800819 virtual ~FakeApplicationHandle() {}
820
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000821 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700822
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500823 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
824 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700825 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800826};
827
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800828class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800829public:
Garfield Tan15601662020-09-22 15:32:38 -0700830 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800831 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700832 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800833 }
834
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800835 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700836 InputEvent* event;
837 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
838 if (!consumeSeq) {
839 return nullptr;
840 }
841 finishEvent(*consumeSeq);
842 return event;
843 }
844
845 /**
846 * Receive an event without acknowledging it.
847 * Return the sequence number that could later be used to send finished signal.
848 */
849 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800850 uint32_t consumeSeq;
851 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800852
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800853 std::chrono::time_point start = std::chrono::steady_clock::now();
854 status_t status = WOULD_BLOCK;
855 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800856 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800857 &event);
858 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
859 if (elapsed > 100ms) {
860 break;
861 }
862 }
863
864 if (status == WOULD_BLOCK) {
865 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700866 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800867 }
868
869 if (status != OK) {
870 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700871 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800872 }
873 if (event == nullptr) {
874 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700875 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800876 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700877 if (outEvent != nullptr) {
878 *outEvent = event;
879 }
880 return consumeSeq;
881 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800882
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700883 /**
884 * To be used together with "receiveEvent" to complete the consumption of an event.
885 */
886 void finishEvent(uint32_t consumeSeq) {
887 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
888 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800889 }
890
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000891 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
892 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
893 ASSERT_EQ(OK, status);
894 }
895
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000896 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
897 std::optional<int32_t> expectedDisplayId,
898 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800899 InputEvent* event = consume();
900
901 ASSERT_NE(nullptr, event) << mName.c_str()
902 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800903 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800905 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800906
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000907 if (expectedDisplayId.has_value()) {
908 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
909 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800910
Tiger Huang8664f8c2018-10-11 19:14:35 +0800911 switch (expectedEventType) {
912 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800913 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
914 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000915 if (expectedFlags.has_value()) {
916 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
917 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800918 break;
919 }
920 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800921 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000922 assertMotionAction(expectedAction, motionEvent.getAction());
923
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000924 if (expectedFlags.has_value()) {
925 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
926 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800927 break;
928 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100929 case AINPUT_EVENT_TYPE_FOCUS: {
930 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
931 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800932 case AINPUT_EVENT_TYPE_CAPTURE: {
933 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
934 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000935 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
936 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
937 }
arthurhungb89ccb02020-12-30 16:19:01 +0800938 case AINPUT_EVENT_TYPE_DRAG: {
939 FAIL() << "Use 'consumeDragEvent' for DRAG events";
940 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800941 default: {
942 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
943 }
944 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800945 }
946
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100947 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
948 InputEvent* event = consume();
949 ASSERT_NE(nullptr, event) << mName.c_str()
950 << ": consumer should have returned non-NULL event.";
951 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
952 << "Got " << inputEventTypeToString(event->getType())
953 << " event instead of FOCUS event";
954
955 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
956 << mName.c_str() << ": event displayId should always be NONE.";
957
958 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
959 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100960 }
961
Prabir Pradhan99987712020-11-10 18:43:05 -0800962 void consumeCaptureEvent(bool hasCapture) {
963 const InputEvent* event = consume();
964 ASSERT_NE(nullptr, event) << mName.c_str()
965 << ": consumer should have returned non-NULL event.";
966 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
967 << "Got " << inputEventTypeToString(event->getType())
968 << " event instead of CAPTURE event";
969
970 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
971 << mName.c_str() << ": event displayId should always be NONE.";
972
973 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
974 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
975 }
976
arthurhungb89ccb02020-12-30 16:19:01 +0800977 void consumeDragEvent(bool isExiting, float x, float y) {
978 const InputEvent* event = consume();
979 ASSERT_NE(nullptr, event) << mName.c_str()
980 << ": consumer should have returned non-NULL event.";
981 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
982 << "Got " << inputEventTypeToString(event->getType())
983 << " event instead of DRAG event";
984
985 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
986 << mName.c_str() << ": event displayId should always be NONE.";
987
988 const auto& dragEvent = static_cast<const DragEvent&>(*event);
989 EXPECT_EQ(isExiting, dragEvent.isExiting());
990 EXPECT_EQ(x, dragEvent.getX());
991 EXPECT_EQ(y, dragEvent.getY());
992 }
993
Antonio Kantekf16f2832021-09-28 04:39:20 +0000994 void consumeTouchModeEvent(bool inTouchMode) {
995 const InputEvent* event = consume();
996 ASSERT_NE(nullptr, event) << mName.c_str()
997 << ": consumer should have returned non-NULL event.";
998 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
999 << "Got " << inputEventTypeToString(event->getType())
1000 << " event instead of TOUCH_MODE event";
1001
1002 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1003 << mName.c_str() << ": event displayId should always be NONE.";
1004 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1005 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1006 }
1007
chaviwd1c23182019-12-20 18:44:56 -08001008 void assertNoEvents() {
1009 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001010 if (event == nullptr) {
1011 return;
1012 }
1013 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1014 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1015 ADD_FAILURE() << "Received key event "
1016 << KeyEvent::actionToString(keyEvent.getAction());
1017 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1018 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1019 ADD_FAILURE() << "Received motion event "
1020 << MotionEvent::actionToString(motionEvent.getAction());
1021 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1022 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1023 ADD_FAILURE() << "Received focus event, hasFocus = "
1024 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001025 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1026 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1027 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1028 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001029 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1030 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1031 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1032 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 }
1034 FAIL() << mName.c_str()
1035 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001036 }
1037
1038 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1039
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001040 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1041
chaviwd1c23182019-12-20 18:44:56 -08001042protected:
1043 std::unique_ptr<InputConsumer> mConsumer;
1044 PreallocatedInputEventFactory mEventFactory;
1045
1046 std::string mName;
1047};
1048
chaviw3277faf2021-05-19 16:45:23 -05001049class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001050public:
1051 static const int32_t WIDTH = 600;
1052 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001053
Chris Yea209fde2020-07-22 13:54:51 -07001054 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001055 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001056 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001057 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001058 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001059 base::Result<std::unique_ptr<InputChannel>> channel =
1060 dispatcher->createInputChannel(name);
1061 token = (*channel)->getConnectionToken();
1062 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001063 }
1064
1065 inputApplicationHandle->updateInfo();
1066 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1067
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001068 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001069 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001070 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001071 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001072 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001073 mInfo.frameLeft = 0;
1074 mInfo.frameTop = 0;
1075 mInfo.frameRight = WIDTH;
1076 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001077 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001078 mInfo.globalScaleFactor = 1.0;
1079 mInfo.touchableRegion.clear();
1080 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001081 mInfo.ownerPid = WINDOW_PID;
1082 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001083 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001084 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001085 }
1086
Arthur Hungabbb9d82021-09-01 14:52:30 +00001087 sp<FakeWindowHandle> clone(
1088 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001089 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001090 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001091 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1092 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001093 return handle;
1094 }
1095
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001096 void setTouchable(bool touchable) {
1097 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1098 }
chaviwd1c23182019-12-20 18:44:56 -08001099
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001100 void setFocusable(bool focusable) {
1101 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1102 }
1103
1104 void setVisible(bool visible) {
1105 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1106 }
Vishnu Nair958da932020-08-21 17:12:37 -07001107
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001108 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001109 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001110 }
1111
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001112 void setPaused(bool paused) {
1113 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1114 }
1115
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001116 void setPreventSplitting(bool preventSplitting) {
1117 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001118 }
1119
1120 void setSlippery(bool slippery) {
1121 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1122 }
1123
1124 void setWatchOutsideTouch(bool watchOutside) {
1125 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1126 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001127
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001128 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1129
1130 void setInterceptsStylus(bool interceptsStylus) {
1131 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1132 }
1133
1134 void setDropInput(bool dropInput) {
1135 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1136 }
1137
1138 void setDropInputIfObscured(bool dropInputIfObscured) {
1139 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1140 }
1141
1142 void setNoInputChannel(bool noInputChannel) {
1143 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1144 }
1145
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001146 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1147
chaviw3277faf2021-05-19 16:45:23 -05001148 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001149
Bernardo Rufino7393d172021-02-26 13:56:11 +00001150 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1151
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001152 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001153 mInfo.frameLeft = frame.left;
1154 mInfo.frameTop = frame.top;
1155 mInfo.frameRight = frame.right;
1156 mInfo.frameBottom = frame.bottom;
1157 mInfo.touchableRegion.clear();
1158 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001159
1160 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1161 ui::Transform translate;
1162 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1163 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001164 }
1165
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001166 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1167
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001168 void setIsWallpaper(bool isWallpaper) {
1169 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1170 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001171
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001172 void setDupTouchToWallpaper(bool hasWallpaper) {
1173 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1174 }
chaviwd1c23182019-12-20 18:44:56 -08001175
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001176 void setTrustedOverlay(bool trustedOverlay) {
1177 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1178 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001179
chaviw9eaa22c2020-07-01 16:21:27 -07001180 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1181 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1182 }
1183
1184 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001185
yunho.shinf4a80b82020-11-16 21:13:57 +09001186 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1187
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001188 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1189 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1190 expectedFlags);
1191 }
1192
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001193 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1194 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1195 }
1196
Svet Ganov5d3bc372020-01-26 23:11:07 -08001197 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001198 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001199 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1200 expectedFlags);
1201 }
1202
1203 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001204 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001205 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1206 expectedFlags);
1207 }
1208
1209 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001210 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001211 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1212 }
1213
1214 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1215 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001216 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1217 expectedFlags);
1218 }
1219
Svet Ganov5d3bc372020-01-26 23:11:07 -08001220 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001221 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1222 int32_t expectedFlags = 0) {
1223 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1224 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001225 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1226 }
1227
1228 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001229 int32_t expectedFlags = 0) {
1230 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1231 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001232 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1233 }
1234
1235 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001236 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001237 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1238 expectedFlags);
1239 }
1240
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001241 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1242 int32_t expectedFlags = 0) {
1243 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1244 expectedFlags);
1245 }
1246
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001247 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1248 int32_t expectedFlags = 0) {
1249 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001250 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001251 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1252 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1253 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1254 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1255 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1256 }
1257
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001258 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1259 ASSERT_NE(mInputReceiver, nullptr)
1260 << "Cannot consume events from a window with no receiver";
1261 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1262 }
1263
Prabir Pradhan99987712020-11-10 18:43:05 -08001264 void consumeCaptureEvent(bool hasCapture) {
1265 ASSERT_NE(mInputReceiver, nullptr)
1266 << "Cannot consume events from a window with no receiver";
1267 mInputReceiver->consumeCaptureEvent(hasCapture);
1268 }
1269
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001270 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1271 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001272 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001273 ASSERT_THAT(*motionEvent, matcher);
1274 }
1275
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001276 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1277 std::optional<int32_t> expectedDisplayId,
1278 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001279 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1280 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1281 expectedFlags);
1282 }
1283
arthurhungb89ccb02020-12-30 16:19:01 +08001284 void consumeDragEvent(bool isExiting, float x, float y) {
1285 mInputReceiver->consumeDragEvent(isExiting, x, y);
1286 }
1287
Antonio Kantekf16f2832021-09-28 04:39:20 +00001288 void consumeTouchModeEvent(bool inTouchMode) {
1289 ASSERT_NE(mInputReceiver, nullptr)
1290 << "Cannot consume events from a window with no receiver";
1291 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1292 }
1293
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001294 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001295 if (mInputReceiver == nullptr) {
1296 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1297 return std::nullopt;
1298 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001299 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001300 }
1301
1302 void finishEvent(uint32_t sequenceNum) {
1303 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1304 mInputReceiver->finishEvent(sequenceNum);
1305 }
1306
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001307 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1308 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1309 mInputReceiver->sendTimeline(inputEventId, timeline);
1310 }
1311
chaviwaf87b3e2019-10-01 16:59:28 -07001312 InputEvent* consume() {
1313 if (mInputReceiver == nullptr) {
1314 return nullptr;
1315 }
1316 return mInputReceiver->consume();
1317 }
1318
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001319 MotionEvent* consumeMotion() {
1320 InputEvent* event = consume();
1321 if (event == nullptr) {
1322 ADD_FAILURE() << "Consume failed : no event";
1323 return nullptr;
1324 }
1325 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1326 ADD_FAILURE() << "Instead of motion event, got "
1327 << inputEventTypeToString(event->getType());
1328 return nullptr;
1329 }
1330 return static_cast<MotionEvent*>(event);
1331 }
1332
Arthur Hungb92218b2018-08-14 12:00:21 +08001333 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001334 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001335 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001336 return; // Can't receive events if the window does not have input channel
1337 }
1338 ASSERT_NE(nullptr, mInputReceiver)
1339 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001340 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001341 }
1342
chaviwaf87b3e2019-10-01 16:59:28 -07001343 sp<IBinder> getToken() { return mInfo.token; }
1344
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345 const std::string& getName() { return mName; }
1346
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001347 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1348 mInfo.ownerPid = ownerPid;
1349 mInfo.ownerUid = ownerUid;
1350 }
1351
Prabir Pradhanedd96402022-02-15 01:46:16 -08001352 int32_t getPid() const { return mInfo.ownerPid; }
1353
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001354 void destroyReceiver() { mInputReceiver = nullptr; }
1355
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001356 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1357
chaviwd1c23182019-12-20 18:44:56 -08001358private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001359 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001360 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001361 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001362};
1363
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001364std::atomic<int32_t> FakeWindowHandle::sId{1};
1365
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001366static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001367 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001368 int32_t displayId = ADISPLAY_ID_NONE,
1369 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001370 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001371 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1372 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001373 KeyEvent event;
1374 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1375
1376 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001377 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001378 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1379 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001380
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001381 if (!allowKeyRepeat) {
1382 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1383 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001384 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001385 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001386}
1387
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001388static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001390 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1391}
1392
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001393// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1394// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1395// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001396static InputEventInjectionResult injectKeyDownNoRepeat(
1397 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001398 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1399 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1400 /* allowKeyRepeat */ false);
1401}
1402
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001403static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001405 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1406}
1407
Garfield Tandf26e862020-07-01 20:18:19 -07001408class PointerBuilder {
1409public:
1410 PointerBuilder(int32_t id, int32_t toolType) {
1411 mProperties.clear();
1412 mProperties.id = id;
1413 mProperties.toolType = toolType;
1414 mCoords.clear();
1415 }
1416
1417 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1418
1419 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1420
1421 PointerBuilder& axis(int32_t axis, float value) {
1422 mCoords.setAxisValue(axis, value);
1423 return *this;
1424 }
1425
1426 PointerProperties buildProperties() const { return mProperties; }
1427
1428 PointerCoords buildCoords() const { return mCoords; }
1429
1430private:
1431 PointerProperties mProperties;
1432 PointerCoords mCoords;
1433};
1434
1435class MotionEventBuilder {
1436public:
1437 MotionEventBuilder(int32_t action, int32_t source) {
1438 mAction = action;
1439 mSource = source;
1440 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1441 }
1442
1443 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1444 mEventTime = eventTime;
1445 return *this;
1446 }
1447
1448 MotionEventBuilder& displayId(int32_t displayId) {
1449 mDisplayId = displayId;
1450 return *this;
1451 }
1452
1453 MotionEventBuilder& actionButton(int32_t actionButton) {
1454 mActionButton = actionButton;
1455 return *this;
1456 }
1457
arthurhung6d4bed92021-03-17 11:59:33 +08001458 MotionEventBuilder& buttonState(int32_t buttonState) {
1459 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001460 return *this;
1461 }
1462
1463 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1464 mRawXCursorPosition = rawXCursorPosition;
1465 return *this;
1466 }
1467
1468 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1469 mRawYCursorPosition = rawYCursorPosition;
1470 return *this;
1471 }
1472
1473 MotionEventBuilder& pointer(PointerBuilder pointer) {
1474 mPointers.push_back(pointer);
1475 return *this;
1476 }
1477
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001478 MotionEventBuilder& addFlag(uint32_t flags) {
1479 mFlags |= flags;
1480 return *this;
1481 }
1482
Garfield Tandf26e862020-07-01 20:18:19 -07001483 MotionEvent build() {
1484 std::vector<PointerProperties> pointerProperties;
1485 std::vector<PointerCoords> pointerCoords;
1486 for (const PointerBuilder& pointer : mPointers) {
1487 pointerProperties.push_back(pointer.buildProperties());
1488 pointerCoords.push_back(pointer.buildCoords());
1489 }
1490
1491 // Set mouse cursor position for the most common cases to avoid boilerplate.
1492 if (mSource == AINPUT_SOURCE_MOUSE &&
1493 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1494 mPointers.size() == 1) {
1495 mRawXCursorPosition = pointerCoords[0].getX();
1496 mRawYCursorPosition = pointerCoords[0].getY();
1497 }
1498
1499 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001500 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001501 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001502 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001503 mButtonState, MotionClassification::NONE, identityTransform,
1504 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001505 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1506 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001507
1508 return event;
1509 }
1510
1511private:
1512 int32_t mAction;
1513 int32_t mSource;
1514 nsecs_t mEventTime;
1515 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1516 int32_t mActionButton{0};
1517 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001518 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001519 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1520 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1521
1522 std::vector<PointerBuilder> mPointers;
1523};
1524
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001525static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001526 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001527 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001528 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1529 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1530 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1531 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001532}
1533
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001534static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001535 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001536 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001537 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001538 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1539 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001540 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001541 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1542 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001543 MotionEvent event = MotionEventBuilder(action, source)
1544 .displayId(displayId)
1545 .eventTime(eventTime)
1546 .rawXCursorPosition(cursorPosition.x)
1547 .rawYCursorPosition(cursorPosition.y)
1548 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1549 .x(position.x)
1550 .y(position.y))
1551 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001552
1553 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001554 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1555 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001556}
1557
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001558static InputEventInjectionResult injectMotionDown(
1559 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1560 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001561 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001562}
1563
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001564static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 int32_t source, int32_t displayId,
1566 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001567 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001568}
1569
Jackal Guof9696682018-10-05 12:23:23 +08001570static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1571 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1572 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001573 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1574 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1575 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001576
1577 return args;
1578}
1579
chaviwd1c23182019-12-20 18:44:56 -08001580static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1581 const std::vector<PointF>& points) {
1582 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001583 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1584 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1585 }
1586
chaviwd1c23182019-12-20 18:44:56 -08001587 PointerProperties pointerProperties[pointerCount];
1588 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001589
chaviwd1c23182019-12-20 18:44:56 -08001590 for (size_t i = 0; i < pointerCount; i++) {
1591 pointerProperties[i].clear();
1592 pointerProperties[i].id = i;
1593 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001594
chaviwd1c23182019-12-20 18:44:56 -08001595 pointerCoords[i].clear();
1596 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1597 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1598 }
Jackal Guof9696682018-10-05 12:23:23 +08001599
1600 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1601 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001602 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001603 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1604 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001605 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1606 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001607 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1608 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001609
1610 return args;
1611}
1612
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001613static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1614 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1615}
1616
chaviwd1c23182019-12-20 18:44:56 -08001617static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1618 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1619}
1620
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001621static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1622 const PointerCaptureRequest& request) {
1623 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001624}
1625
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001626/**
1627 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1628 * broken channel.
1629 */
1630TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1631 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1632 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001633 sp<FakeWindowHandle>::make(application, mDispatcher,
1634 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001635
1636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1637
1638 // Window closes its channel, but the window remains.
1639 window->destroyReceiver();
1640 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1641}
1642
Arthur Hungb92218b2018-08-14 12:00:21 +08001643TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001645 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1646 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001647
Arthur Hung72d8dc32020-03-28 00:48:39 +00001648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1650 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001652
1653 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001654 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001655}
1656
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001657TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1658 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001659 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1660 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001661
1662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1663 // Inject a MotionEvent to an unknown display.
1664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1665 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1667
1668 // Window should receive motion event.
1669 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1670}
1671
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001672/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001673 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001674 * This test serves as a sanity check for the next test, where setInputWindows is
1675 * called twice.
1676 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001677TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001678 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001679 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1680 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001681 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001682
1683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001685 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1686 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001688
1689 // Window should receive motion event.
1690 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1691}
1692
1693/**
1694 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001695 */
1696TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001697 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001698 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1699 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001700 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001701
1702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001705 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1706 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001707 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001708
1709 // Window should receive motion event.
1710 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1711}
1712
Arthur Hungb92218b2018-08-14 12:00:21 +08001713// The foreground window should receive the first touch down event.
1714TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001715 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001716 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001717 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001718 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001719 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001720
Arthur Hung72d8dc32020-03-28 00:48:39 +00001721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001725
1726 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001727 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001728 windowSecond->assertNoEvents();
1729}
1730
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001731/**
1732 * Two windows: A top window, and a wallpaper behind the window.
1733 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1734 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001735 * 1. foregroundWindow <-- dup touch to wallpaper
1736 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001737 */
1738TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1740 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001741 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001742 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001743 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001744 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001745 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001746
1747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1749 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1750 {100, 200}))
1751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1752
1753 // Both foreground window and its wallpaper should receive the touch down
1754 foregroundWindow->consumeMotionDown();
1755 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1756
1757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1758 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1759 ADISPLAY_ID_DEFAULT, {110, 200}))
1760 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1761
1762 foregroundWindow->consumeMotionMove();
1763 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1764
1765 // Now the foreground window goes away, but the wallpaper stays
1766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1767 foregroundWindow->consumeMotionCancel();
1768 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1769 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1770}
1771
1772/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001773 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1774 * with the following differences:
1775 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1776 * clean up the connection.
1777 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1778 * Ensure that there's no crash in the dispatcher.
1779 */
1780TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1781 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1782 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001783 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001784 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001785 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001786 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001787 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001788
1789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1791 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1792 {100, 200}))
1793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1794
1795 // Both foreground window and its wallpaper should receive the touch down
1796 foregroundWindow->consumeMotionDown();
1797 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1798
1799 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1800 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1801 ADISPLAY_ID_DEFAULT, {110, 200}))
1802 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1803
1804 foregroundWindow->consumeMotionMove();
1805 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1806
1807 // Wallpaper closes its channel, but the window remains.
1808 wallpaperWindow->destroyReceiver();
1809 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1810
1811 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1812 // is no longer valid.
1813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1814 foregroundWindow->consumeMotionCancel();
1815}
1816
Arthur Hungc539dbb2022-12-08 07:45:36 +00001817class ShouldSplitTouchFixture : public InputDispatcherTest,
1818 public ::testing::WithParamInterface<bool> {};
1819INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1820 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001821/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001822 * A single window that receives touch (on top), and a wallpaper window underneath it.
1823 * The top window gets a multitouch gesture.
1824 * Ensure that wallpaper gets the same gesture.
1825 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00001826TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001827 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00001828 sp<FakeWindowHandle> foregroundWindow =
1829 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1830 foregroundWindow->setDupTouchToWallpaper(true);
1831 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001832
1833 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001834 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001835 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001836
Arthur Hungc539dbb2022-12-08 07:45:36 +00001837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001838
1839 // Touch down on top window
1840 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1841 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1842 {100, 100}))
1843 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1844
1845 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00001846 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001847 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1848
1849 // Second finger down on the top window
1850 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001851 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001852 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1853 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1854 .x(100)
1855 .y(100))
1856 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1857 .x(150)
1858 .y(150))
1859 .build();
1860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1861 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1862 InputEventInjectionSync::WAIT_FOR_RESULT))
1863 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1864
Arthur Hungc539dbb2022-12-08 07:45:36 +00001865 foregroundWindow->consumeMotionPointerDown(1 /* pointerIndex */);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001866 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1867 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00001868
1869 const MotionEvent secondFingerUpEvent =
1870 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1871 .displayId(ADISPLAY_ID_DEFAULT)
1872 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1873 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1874 .x(100)
1875 .y(100))
1876 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1877 .x(150)
1878 .y(150))
1879 .build();
1880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1881 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1882 InputEventInjectionSync::WAIT_FOR_RESULT))
1883 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1884 foregroundWindow->consumeMotionPointerUp(0);
1885 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1886
1887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1888 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1889 {100, 100}))
1890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1891 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1892 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001893}
1894
1895/**
1896 * Two windows: a window on the left and window on the right.
1897 * A third window, wallpaper, is behind both windows, and spans both top windows.
1898 * The first touch down goes to the left window. A second pointer touches down on the right window.
1899 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1900 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1901 * ACTION_POINTER_DOWN(1).
1902 */
1903TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1904 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1905 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001906 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001907 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001908 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001909
1910 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001911 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001912 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001913 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001914
1915 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001916 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001917 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001918 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001919
1920 mDispatcher->setInputWindows(
1921 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1922
1923 // Touch down on left window
1924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1926 {100, 100}))
1927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1928
1929 // Both foreground window and its wallpaper should receive the touch down
1930 leftWindow->consumeMotionDown();
1931 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1932
1933 // Second finger down on the right window
1934 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001935 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001936 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1937 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1938 .x(100)
1939 .y(100))
1940 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1941 .x(300)
1942 .y(100))
1943 .build();
1944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1945 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1946 InputEventInjectionSync::WAIT_FOR_RESULT))
1947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1948
1949 leftWindow->consumeMotionMove();
1950 // Since the touch is split, right window gets ACTION_DOWN
1951 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1952 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1953 expectedWallpaperFlags);
1954
1955 // Now, leftWindow, which received the first finger, disappears.
1956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1957 leftWindow->consumeMotionCancel();
1958 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1959 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1960
1961 // The pointer that's still down on the right window moves, and goes to the right window only.
1962 // As far as the dispatcher's concerned though, both pointers are still present.
1963 const MotionEvent secondFingerMoveEvent =
1964 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1965 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1966 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1967 .x(100)
1968 .y(100))
1969 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1970 .x(310)
1971 .y(110))
1972 .build();
1973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1974 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1975 InputEventInjectionSync::WAIT_FOR_RESULT));
1976 rightWindow->consumeMotionMove();
1977
1978 leftWindow->assertNoEvents();
1979 rightWindow->assertNoEvents();
1980 wallpaperWindow->assertNoEvents();
1981}
1982
Arthur Hungc539dbb2022-12-08 07:45:36 +00001983/**
1984 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
1985 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
1986 * The right window should receive ACTION_DOWN.
1987 */
1988TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00001989 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00001990 sp<FakeWindowHandle> leftWindow =
1991 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1992 leftWindow->setFrame(Rect(0, 0, 200, 200));
1993 leftWindow->setDupTouchToWallpaper(true);
1994 leftWindow->setSlippery(true);
1995
1996 sp<FakeWindowHandle> rightWindow =
1997 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1998 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00001999
2000 sp<FakeWindowHandle> wallpaperWindow =
2001 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2002 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002003
Arthur Hungc539dbb2022-12-08 07:45:36 +00002004 mDispatcher->setInputWindows(
2005 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002006
Arthur Hungc539dbb2022-12-08 07:45:36 +00002007 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2009 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002010 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002012
2013 // Both foreground window and its wallpaper should receive the touch down
2014 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002015 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2016
Arthur Hungc539dbb2022-12-08 07:45:36 +00002017 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002019 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2020 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2022
Arthur Hungc539dbb2022-12-08 07:45:36 +00002023 leftWindow->consumeMotionCancel();
2024 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2025 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002026}
2027
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002028/**
2029 * On the display, have a single window, and also an area where there's no window.
2030 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2031 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2032 */
2033TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2034 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2035 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002036 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002037
2038 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2039 NotifyMotionArgs args;
2040
2041 // Touch down on the empty space
2042 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2043
2044 mDispatcher->waitForIdle();
2045 window->assertNoEvents();
2046
2047 // Now touch down on the window with another pointer
2048 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2049 mDispatcher->waitForIdle();
2050 window->consumeMotionDown();
2051}
2052
2053/**
2054 * Same test as above, but instead of touching the empty space, the first touch goes to
2055 * non-touchable window.
2056 */
2057TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2058 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2059 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002060 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002061 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2062 window1->setTouchable(false);
2063 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002064 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002065 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2066
2067 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2068
2069 NotifyMotionArgs args;
2070 // Touch down on the non-touchable window
2071 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2072
2073 mDispatcher->waitForIdle();
2074 window1->assertNoEvents();
2075 window2->assertNoEvents();
2076
2077 // Now touch down on the window with another pointer
2078 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2079 mDispatcher->waitForIdle();
2080 window2->consumeMotionDown();
2081}
2082
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002083/**
2084 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2085 * to the event time of the first ACTION_DOWN sent to the particular window.
2086 */
2087TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2089 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002090 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002091 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2092 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002093 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002094 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2095
2096 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2097
2098 NotifyMotionArgs args;
2099 // Touch down on the first window
2100 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2101
2102 mDispatcher->waitForIdle();
2103 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002104 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002105 window2->assertNoEvents();
2106 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2107 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2108 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2109
2110 // Now touch down on the window with another pointer
2111 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2112 mDispatcher->waitForIdle();
2113 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002114 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002115 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2116 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2117 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2118 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2119
2120 // Now move the pointer on the second window
2121 mDispatcher->notifyMotion(
2122 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2123 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002124 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002125
2126 // Now add new touch down on the second window
2127 mDispatcher->notifyMotion(
2128 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2129 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002130 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002131
2132 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2133 window1->consumeMotionMove();
2134 window1->assertNoEvents();
2135
2136 // Now move the pointer on the first window
2137 mDispatcher->notifyMotion(
2138 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2139 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002140 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002141
2142 mDispatcher->notifyMotion(&(
2143 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2144 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002145 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002146}
2147
Garfield Tandf26e862020-07-01 20:18:19 -07002148TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002149 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002150 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002151 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002152 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002153 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002154 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002155 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002156
2157 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2158
2159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2160
2161 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002163 injectMotionEvent(mDispatcher,
2164 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2165 AINPUT_SOURCE_MOUSE)
2166 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2167 .x(900)
2168 .y(400))
2169 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002170 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002171 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE));
Garfield Tandf26e862020-07-01 20:18:19 -07002172
2173 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002174 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002175 injectMotionEvent(mDispatcher,
2176 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2177 AINPUT_SOURCE_MOUSE)
2178 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2179 .x(300)
2180 .y(400))
2181 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002182 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2183 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002184 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE));
Garfield Tandf26e862020-07-01 20:18:19 -07002185
2186 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002188 injectMotionEvent(mDispatcher,
2189 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2190 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2191 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2192 .x(300)
2193 .y(400))
2194 .build()));
2195 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2196
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002198 injectMotionEvent(mDispatcher,
2199 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2200 AINPUT_SOURCE_MOUSE)
2201 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2202 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2203 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2204 .x(300)
2205 .y(400))
2206 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002207 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002208
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002209 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002210 injectMotionEvent(mDispatcher,
2211 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2212 AINPUT_SOURCE_MOUSE)
2213 .buttonState(0)
2214 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2215 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2216 .x(300)
2217 .y(400))
2218 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002219 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002220
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002222 injectMotionEvent(mDispatcher,
2223 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2224 .buttonState(0)
2225 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2226 .x(300)
2227 .y(400))
2228 .build()));
2229 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2230
2231 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002233 injectMotionEvent(mDispatcher,
2234 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2235 AINPUT_SOURCE_MOUSE)
2236 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2237 .x(900)
2238 .y(400))
2239 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002240 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2241 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002242 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002243
2244 // No more events
2245 windowLeft->assertNoEvents();
2246 windowRight->assertNoEvents();
2247}
2248
2249TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
2250 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2251
2252 sp<FakeWindowHandle> spyWindow =
2253 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2254 spyWindow->setFrame(Rect(0, 0, 600, 800));
2255 spyWindow->setTrustedOverlay(true);
2256 spyWindow->setSpy(true);
2257 sp<FakeWindowHandle> window =
2258 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2259 window->setFrame(Rect(0, 0, 600, 800));
2260
2261 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2263
2264 // Send mouse cursor to the window
2265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2266 injectMotionEvent(mDispatcher,
2267 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2268 AINPUT_SOURCE_MOUSE)
2269 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2270 .x(100)
2271 .y(100))
2272 .build()));
2273
2274 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2275 WithSource(AINPUT_SOURCE_MOUSE)));
2276 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2277 WithSource(AINPUT_SOURCE_MOUSE)));
2278
2279 window->assertNoEvents();
2280 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07002281}
2282
2283// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2284// directly in this test.
2285TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002286 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002287 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002288 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002289 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002290
2291 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2292
2293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2294
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002296 injectMotionEvent(mDispatcher,
2297 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2298 AINPUT_SOURCE_MOUSE)
2299 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2300 .x(300)
2301 .y(400))
2302 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002303 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002304
Garfield Tandf26e862020-07-01 20:18:19 -07002305 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002307 injectMotionEvent(mDispatcher,
2308 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2309 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2310 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2311 .x(300)
2312 .y(400))
2313 .build()));
2314 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2315
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002317 injectMotionEvent(mDispatcher,
2318 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2319 AINPUT_SOURCE_MOUSE)
2320 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2321 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2322 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2323 .x(300)
2324 .y(400))
2325 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002326 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002327
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002329 injectMotionEvent(mDispatcher,
2330 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2331 AINPUT_SOURCE_MOUSE)
2332 .buttonState(0)
2333 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2334 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2335 .x(300)
2336 .y(400))
2337 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002338 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002339
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002341 injectMotionEvent(mDispatcher,
2342 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2343 .buttonState(0)
2344 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2345 .x(300)
2346 .y(400))
2347 .build()));
2348 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2349
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002351 injectMotionEvent(mDispatcher,
2352 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2353 AINPUT_SOURCE_MOUSE)
2354 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2355 .x(300)
2356 .y(400))
2357 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002358 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
Garfield Tandf26e862020-07-01 20:18:19 -07002359}
2360
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002361/**
2362 * Inject a mouse hover event followed by a tap from touchscreen.
Sam Dubey39d37cf2022-12-07 18:05:35 +00002363 * In the current implementation, the tap does not cause a HOVER_EXIT event.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002364 */
2365TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2366 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2367 sp<FakeWindowHandle> window =
2368 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2369 window->setFrame(Rect(0, 0, 100, 100));
2370
2371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2372
2373 // Inject a hover_move from mouse.
2374 NotifyMotionArgs motionArgs =
2375 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2376 ADISPLAY_ID_DEFAULT, {{50, 50}});
2377 motionArgs.xCursorPosition = 50;
2378 motionArgs.yCursorPosition = 50;
2379 mDispatcher->notifyMotion(&motionArgs);
2380 ASSERT_NO_FATAL_FAILURE(
2381 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2382 WithSource(AINPUT_SOURCE_MOUSE))));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002383 ASSERT_NO_FATAL_FAILURE(
2384 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2385 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002386
2387 // Tap on the window
2388 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2389 ADISPLAY_ID_DEFAULT, {{10, 10}});
2390 mDispatcher->notifyMotion(&motionArgs);
2391 ASSERT_NO_FATAL_FAILURE(
2392 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2393 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2394
2395 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2396 ADISPLAY_ID_DEFAULT, {{10, 10}});
2397 mDispatcher->notifyMotion(&motionArgs);
2398 ASSERT_NO_FATAL_FAILURE(
2399 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2400 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2401}
2402
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002403TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2404 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2405 sp<FakeWindowHandle> windowDefaultDisplay =
2406 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2407 ADISPLAY_ID_DEFAULT);
2408 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2409 sp<FakeWindowHandle> windowSecondDisplay =
2410 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2411 SECOND_DISPLAY_ID);
2412 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2413
2414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2415 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2416
2417 // Set cursor position in window in default display and check that hover enter and move
2418 // events are generated.
2419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2420 injectMotionEvent(mDispatcher,
2421 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2422 AINPUT_SOURCE_MOUSE)
2423 .displayId(ADISPLAY_ID_DEFAULT)
2424 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2425 .x(300)
2426 .y(600))
2427 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002428 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Sam Dubey39d37cf2022-12-07 18:05:35 +00002429 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002430
2431 // Remove all windows in secondary display and check that no event happens on window in
2432 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002433 mDispatcher->setInputWindows(
2434 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002435 windowDefaultDisplay->assertNoEvents();
2436
2437 // Move cursor position in window in default display and check that only hover move
2438 // event is generated and not hover enter event.
2439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2440 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2442 injectMotionEvent(mDispatcher,
2443 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2444 AINPUT_SOURCE_MOUSE)
2445 .displayId(ADISPLAY_ID_DEFAULT)
2446 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2447 .x(400)
2448 .y(700))
2449 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002450 windowDefaultDisplay->consumeMotionEvent(
2451 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2452 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002453 windowDefaultDisplay->assertNoEvents();
2454}
2455
Garfield Tan00f511d2019-06-12 16:55:40 -07002456TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002457 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002458
2459 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002460 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002461 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002462 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002463 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002464 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002465
2466 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2467
Arthur Hung72d8dc32020-03-28 00:48:39 +00002468 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002469
2470 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2471 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002473 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002474 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002475 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002476 windowRight->assertNoEvents();
2477}
2478
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002479TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002480 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002481 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2482 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002483 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002484
Arthur Hung72d8dc32020-03-28 00:48:39 +00002485 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002486 setFocusedWindow(window);
2487
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002488 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002489
2490 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2491 mDispatcher->notifyKey(&keyArgs);
2492
2493 // Window should receive key down event.
2494 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2495
2496 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2497 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002498 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002499 mDispatcher->notifyDeviceReset(&args);
2500 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2501 AKEY_EVENT_FLAG_CANCELED);
2502}
2503
2504TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002505 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002506 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2507 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002508
Arthur Hung72d8dc32020-03-28 00:48:39 +00002509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002510
2511 NotifyMotionArgs motionArgs =
2512 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2513 ADISPLAY_ID_DEFAULT);
2514 mDispatcher->notifyMotion(&motionArgs);
2515
2516 // Window should receive motion down event.
2517 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2518
2519 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2520 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002521 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002522 mDispatcher->notifyDeviceReset(&args);
2523 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2524 0 /*expectedFlags*/);
2525}
2526
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002527TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2528 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002529 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2530 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002531 window->setFocusable(true);
2532
2533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2534 setFocusedWindow(window);
2535
2536 window->consumeFocusEvent(true);
2537
2538 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2539 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2540 const nsecs_t injectTime = keyArgs.eventTime;
2541 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2542 mDispatcher->notifyKey(&keyArgs);
2543 // The dispatching time should be always greater than or equal to intercept key timeout.
2544 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2545 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2546 std::chrono::nanoseconds(interceptKeyTimeout).count());
2547}
2548
2549TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2550 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002551 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2552 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002553 window->setFocusable(true);
2554
2555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2556 setFocusedWindow(window);
2557
2558 window->consumeFocusEvent(true);
2559
2560 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2561 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2562 mFakePolicy->setInterceptKeyTimeout(150ms);
2563 mDispatcher->notifyKey(&keyDown);
2564 mDispatcher->notifyKey(&keyUp);
2565
2566 // Window should receive key event immediately when same key up.
2567 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2568 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2569}
2570
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002571/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002572 * Two windows. First is a regular window. Second does not overlap with the first, and has
2573 * WATCH_OUTSIDE_TOUCH.
2574 * Both windows are owned by the same UID.
2575 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
2576 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
2577 */
2578TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
2579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2580 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2581 "First Window", ADISPLAY_ID_DEFAULT);
2582 window->setFrame(Rect{0, 0, 100, 100});
2583
2584 sp<FakeWindowHandle> outsideWindow =
2585 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2586 ADISPLAY_ID_DEFAULT);
2587 outsideWindow->setFrame(Rect{100, 100, 200, 200});
2588 outsideWindow->setWatchOutsideTouch(true);
2589 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
2590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
2591
2592 // Tap on first window.
2593 NotifyMotionArgs motionArgs =
2594 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2595 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
2596 mDispatcher->notifyMotion(&motionArgs);
2597 window->consumeMotionDown();
2598 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
2599 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
2600 outsideWindow->consumeMotionEvent(
2601 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
2602}
2603
2604/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002605 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2606 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2607 * ACTION_OUTSIDE event is sent per gesture.
2608 */
2609TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2610 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2611 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002612 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2613 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002614 window->setWatchOutsideTouch(true);
2615 window->setFrame(Rect{0, 0, 100, 100});
2616 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002617 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2618 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002619 secondWindow->setFrame(Rect{100, 100, 200, 200});
2620 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002621 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2622 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002623 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2625
2626 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2627 NotifyMotionArgs motionArgs =
2628 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2629 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2630 mDispatcher->notifyMotion(&motionArgs);
2631 window->assertNoEvents();
2632 secondWindow->assertNoEvents();
2633
2634 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2635 // Now, `window` should get ACTION_OUTSIDE.
2636 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2637 {PointF{-10, -10}, PointF{105, 105}});
2638 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002639 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
2640 window->consumeMotionEvent(
2641 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002642 secondWindow->consumeMotionDown();
2643 thirdWindow->assertNoEvents();
2644
2645 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2646 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2647 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2648 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2649 mDispatcher->notifyMotion(&motionArgs);
2650 window->assertNoEvents();
2651 secondWindow->consumeMotionMove();
2652 thirdWindow->consumeMotionDown();
2653}
2654
Prabir Pradhan814fe082022-07-22 20:22:18 +00002655TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2656 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002657 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2658 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002659 window->setFocusable(true);
2660
2661 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2662 setFocusedWindow(window);
2663
2664 window->consumeFocusEvent(true);
2665
2666 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2667 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2668 mDispatcher->notifyKey(&keyDown);
2669 mDispatcher->notifyKey(&keyUp);
2670
2671 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2672 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2673
2674 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2675 mDispatcher->onWindowInfosChanged({}, {});
2676
2677 window->consumeFocusEvent(false);
2678
2679 mDispatcher->notifyKey(&keyDown);
2680 mDispatcher->notifyKey(&keyUp);
2681 window->assertNoEvents();
2682}
2683
Arthur Hung96483742022-11-15 03:30:48 +00002684TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2685 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2686 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2687 "Fake Window", ADISPLAY_ID_DEFAULT);
2688 // Ensure window is non-split and have some transform.
2689 window->setPreventSplitting(true);
2690 window->setWindowOffset(20, 40);
2691 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2692
2693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2694 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2695 {50, 50}))
2696 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2697 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2698
2699 const MotionEvent secondFingerDownEvent =
2700 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2701 .displayId(ADISPLAY_ID_DEFAULT)
2702 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2703 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2704 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2705 .x(-30)
2706 .y(-50))
2707 .build();
2708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2709 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2710 InputEventInjectionSync::WAIT_FOR_RESULT))
2711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2712
2713 const MotionEvent* event = window->consumeMotion();
2714 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2715 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2716 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2717 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2718 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2719}
2720
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002721/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002722 * Ensure the correct coordinate spaces are used by InputDispatcher.
2723 *
2724 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2725 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2726 * space.
2727 */
2728class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2729public:
2730 void SetUp() override {
2731 InputDispatcherTest::SetUp();
2732 mDisplayInfos.clear();
2733 mWindowInfos.clear();
2734 }
2735
2736 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2737 gui::DisplayInfo info;
2738 info.displayId = displayId;
2739 info.transform = transform;
2740 mDisplayInfos.push_back(std::move(info));
2741 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2742 }
2743
2744 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2745 mWindowInfos.push_back(*windowHandle->getInfo());
2746 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2747 }
2748
2749 // Set up a test scenario where the display has a scaled projection and there are two windows
2750 // on the display.
2751 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2752 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2753 // respectively.
2754 ui::Transform displayTransform;
2755 displayTransform.set(2, 0, 0, 4);
2756 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2757
2758 std::shared_ptr<FakeApplicationHandle> application =
2759 std::make_shared<FakeApplicationHandle>();
2760
2761 // Add two windows to the display. Their frames are represented in the display space.
2762 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002763 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2764 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002765 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2766 addWindow(firstWindow);
2767
2768 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002769 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2770 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002771 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2772 addWindow(secondWindow);
2773 return {std::move(firstWindow), std::move(secondWindow)};
2774 }
2775
2776private:
2777 std::vector<gui::DisplayInfo> mDisplayInfos;
2778 std::vector<gui::WindowInfo> mWindowInfos;
2779};
2780
2781TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2782 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2783 // Send down to the first window. The point is represented in the display space. The point is
2784 // selected so that if the hit test was done with the transform applied to it, then it would
2785 // end up in the incorrect window.
2786 NotifyMotionArgs downMotionArgs =
2787 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2788 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2789 mDispatcher->notifyMotion(&downMotionArgs);
2790
2791 firstWindow->consumeMotionDown();
2792 secondWindow->assertNoEvents();
2793}
2794
2795// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2796// the event should be treated as being in the logical display space.
2797TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2798 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2799 // Send down to the first window. The point is represented in the logical display space. The
2800 // point is selected so that if the hit test was done in logical display space, then it would
2801 // end up in the incorrect window.
2802 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2803 PointF{75 * 2, 55 * 4});
2804
2805 firstWindow->consumeMotionDown();
2806 secondWindow->assertNoEvents();
2807}
2808
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002809// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2810// event should be treated as being in the logical display space.
2811TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2812 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2813
2814 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2815 ui::Transform injectedEventTransform;
2816 injectedEventTransform.set(matrix);
2817 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2818 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2819
2820 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2821 .displayId(ADISPLAY_ID_DEFAULT)
2822 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2823 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2824 .x(untransformedPoint.x)
2825 .y(untransformedPoint.y))
2826 .build();
2827 event.transform(matrix);
2828
2829 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2830 InputEventInjectionSync::WAIT_FOR_RESULT);
2831
2832 firstWindow->consumeMotionDown();
2833 secondWindow->assertNoEvents();
2834}
2835
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002836TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2837 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2838
2839 // Send down to the second window.
2840 NotifyMotionArgs downMotionArgs =
2841 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2842 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2843 mDispatcher->notifyMotion(&downMotionArgs);
2844
2845 firstWindow->assertNoEvents();
2846 const MotionEvent* event = secondWindow->consumeMotion();
2847 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2848
2849 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2850 EXPECT_EQ(300, event->getRawX(0));
2851 EXPECT_EQ(880, event->getRawY(0));
2852
2853 // Ensure that the x and y values are in the window's coordinate space.
2854 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2855 // the logical display space. This will be the origin of the window space.
2856 EXPECT_EQ(100, event->getX(0));
2857 EXPECT_EQ(80, event->getY(0));
2858}
2859
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002860using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2861 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002862
2863class TransferTouchFixture : public InputDispatcherTest,
2864 public ::testing::WithParamInterface<TransferFunction> {};
2865
2866TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002868
2869 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002870 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002871 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2872 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002873 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002874 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002875 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2876 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002877 sp<FakeWindowHandle> wallpaper =
2878 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2879 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002880 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00002881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002882
2883 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002884 NotifyMotionArgs downMotionArgs =
2885 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2886 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002887 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002888
Svet Ganov5d3bc372020-01-26 23:11:07 -08002889 // Only the first window should get the down event
2890 firstWindow->consumeMotionDown();
2891 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002892 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002893
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002894 // Transfer touch to the second window
2895 TransferFunction f = GetParam();
2896 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2897 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002898 // The first window gets cancel and the second gets down
2899 firstWindow->consumeMotionCancel();
2900 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002901 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002902
2903 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002904 NotifyMotionArgs upMotionArgs =
2905 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2906 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002907 mDispatcher->notifyMotion(&upMotionArgs);
2908 // The first window gets no events and the second gets up
2909 firstWindow->assertNoEvents();
2910 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002911 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002912}
2913
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002914/**
2915 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2916 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2917 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2918 * natural to the user.
2919 * In this test, we are sending a pointer to both spy window and first window. We then try to
2920 * transfer touch to the second window. The dispatcher should identify the first window as the
2921 * one that should lose the gesture, and therefore the action should be to move the gesture from
2922 * the first window to the second.
2923 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2924 * the other API, as well.
2925 */
2926TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2927 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2928
2929 // Create a couple of windows + a spy window
2930 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002931 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002932 spyWindow->setTrustedOverlay(true);
2933 spyWindow->setSpy(true);
2934 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002935 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002936 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002937 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002938
2939 // Add the windows to the dispatcher
2940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2941
2942 // Send down to the first window
2943 NotifyMotionArgs downMotionArgs =
2944 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2945 ADISPLAY_ID_DEFAULT);
2946 mDispatcher->notifyMotion(&downMotionArgs);
2947 // Only the first window and spy should get the down event
2948 spyWindow->consumeMotionDown();
2949 firstWindow->consumeMotionDown();
2950
2951 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2952 // if f === 'transferTouch'.
2953 TransferFunction f = GetParam();
2954 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2955 ASSERT_TRUE(success);
2956 // The first window gets cancel and the second gets down
2957 firstWindow->consumeMotionCancel();
2958 secondWindow->consumeMotionDown();
2959
2960 // Send up event to the second window
2961 NotifyMotionArgs upMotionArgs =
2962 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2963 ADISPLAY_ID_DEFAULT);
2964 mDispatcher->notifyMotion(&upMotionArgs);
2965 // The first window gets no events and the second+spy get up
2966 firstWindow->assertNoEvents();
2967 spyWindow->consumeMotionUp();
2968 secondWindow->consumeMotionUp();
2969}
2970
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002971TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002972 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002973
2974 PointF touchPoint = {10, 10};
2975
2976 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002977 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002978 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2979 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002980 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002981 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002982 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2983 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002984 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002985
2986 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002988
2989 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002990 NotifyMotionArgs downMotionArgs =
2991 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2992 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002993 mDispatcher->notifyMotion(&downMotionArgs);
2994 // Only the first window should get the down event
2995 firstWindow->consumeMotionDown();
2996 secondWindow->assertNoEvents();
2997
2998 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002999 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003000 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003001 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003002 mDispatcher->notifyMotion(&pointerDownMotionArgs);
3003 // Only the first window should get the pointer down event
3004 firstWindow->consumeMotionPointerDown(1);
3005 secondWindow->assertNoEvents();
3006
3007 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003008 TransferFunction f = GetParam();
3009 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3010 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003011 // The first window gets cancel and the second gets down and pointer down
3012 firstWindow->consumeMotionCancel();
3013 secondWindow->consumeMotionDown();
3014 secondWindow->consumeMotionPointerDown(1);
3015
3016 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003017 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003018 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003019 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003020 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3021 // The first window gets nothing and the second gets pointer up
3022 firstWindow->assertNoEvents();
3023 secondWindow->consumeMotionPointerUp(1);
3024
3025 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003026 NotifyMotionArgs upMotionArgs =
3027 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3028 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003029 mDispatcher->notifyMotion(&upMotionArgs);
3030 // The first window gets nothing and the second gets up
3031 firstWindow->assertNoEvents();
3032 secondWindow->consumeMotionUp();
3033}
3034
Arthur Hungc539dbb2022-12-08 07:45:36 +00003035TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
3036 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3037
3038 // Create a couple of windows
3039 sp<FakeWindowHandle> firstWindow =
3040 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3041 ADISPLAY_ID_DEFAULT);
3042 firstWindow->setDupTouchToWallpaper(true);
3043 sp<FakeWindowHandle> secondWindow =
3044 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3045 ADISPLAY_ID_DEFAULT);
3046 secondWindow->setDupTouchToWallpaper(true);
3047
3048 sp<FakeWindowHandle> wallpaper1 =
3049 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
3050 wallpaper1->setIsWallpaper(true);
3051
3052 sp<FakeWindowHandle> wallpaper2 =
3053 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
3054 wallpaper2->setIsWallpaper(true);
3055 // Add the windows to the dispatcher
3056 mDispatcher->setInputWindows(
3057 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
3058
3059 // Send down to the first window
3060 NotifyMotionArgs downMotionArgs =
3061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3062 ADISPLAY_ID_DEFAULT);
3063 mDispatcher->notifyMotion(&downMotionArgs);
3064
3065 // Only the first window should get the down event
3066 firstWindow->consumeMotionDown();
3067 secondWindow->assertNoEvents();
3068 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3069 wallpaper2->assertNoEvents();
3070
3071 // Transfer touch focus to the second window
3072 TransferFunction f = GetParam();
3073 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3074 ASSERT_TRUE(success);
3075
3076 // The first window gets cancel and the second gets down
3077 firstWindow->consumeMotionCancel();
3078 secondWindow->consumeMotionDown();
3079 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3080 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3081
3082 // Send up event to the second window
3083 NotifyMotionArgs upMotionArgs =
3084 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3085 ADISPLAY_ID_DEFAULT);
3086 mDispatcher->notifyMotion(&upMotionArgs);
3087 // The first window gets no events and the second gets up
3088 firstWindow->assertNoEvents();
3089 secondWindow->consumeMotionUp();
3090 wallpaper1->assertNoEvents();
3091 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3092}
3093
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003094// For the cases of single pointer touch and two pointers non-split touch, the api's
3095// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
3096// for the case where there are multiple pointers split across several windows.
3097INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
3098 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003099 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3100 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003101 return dispatcher->transferTouch(destChannelToken,
3102 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003103 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003104 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3105 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003106 return dispatcher->transferTouchFocus(from, to,
3107 false /*isDragAndDrop*/);
3108 }));
3109
Svet Ganov5d3bc372020-01-26 23:11:07 -08003110TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003111 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003112
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003113 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003114 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3115 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003116 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003117
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003118 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003119 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3120 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003121 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003122
3123 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003125
3126 PointF pointInFirst = {300, 200};
3127 PointF pointInSecond = {300, 600};
3128
3129 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003130 NotifyMotionArgs firstDownMotionArgs =
3131 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3132 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003133 mDispatcher->notifyMotion(&firstDownMotionArgs);
3134 // Only the first window should get the down event
3135 firstWindow->consumeMotionDown();
3136 secondWindow->assertNoEvents();
3137
3138 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003139 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003140 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003141 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003142 mDispatcher->notifyMotion(&secondDownMotionArgs);
3143 // The first window gets a move and the second a down
3144 firstWindow->consumeMotionMove();
3145 secondWindow->consumeMotionDown();
3146
3147 // Transfer touch focus to the second window
3148 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
3149 // The first window gets cancel and the new gets pointer down (it already saw down)
3150 firstWindow->consumeMotionCancel();
3151 secondWindow->consumeMotionPointerDown(1);
3152
3153 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003154 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003155 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003156 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003157 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3158 // The first window gets nothing and the second gets pointer up
3159 firstWindow->assertNoEvents();
3160 secondWindow->consumeMotionPointerUp(1);
3161
3162 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003163 NotifyMotionArgs upMotionArgs =
3164 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3165 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003166 mDispatcher->notifyMotion(&upMotionArgs);
3167 // The first window gets nothing and the second gets up
3168 firstWindow->assertNoEvents();
3169 secondWindow->consumeMotionUp();
3170}
3171
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003172// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3173// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3174// touch is not supported, so the touch should continue on those windows and the transferred-to
3175// window should get nothing.
3176TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3177 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3178
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003179 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003180 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3181 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003182 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003183
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003184 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003185 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3186 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003187 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003188
3189 // Add the windows to the dispatcher
3190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3191
3192 PointF pointInFirst = {300, 200};
3193 PointF pointInSecond = {300, 600};
3194
3195 // Send down to the first window
3196 NotifyMotionArgs firstDownMotionArgs =
3197 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3198 ADISPLAY_ID_DEFAULT, {pointInFirst});
3199 mDispatcher->notifyMotion(&firstDownMotionArgs);
3200 // Only the first window should get the down event
3201 firstWindow->consumeMotionDown();
3202 secondWindow->assertNoEvents();
3203
3204 // Send down to the second window
3205 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003206 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003207 {pointInFirst, pointInSecond});
3208 mDispatcher->notifyMotion(&secondDownMotionArgs);
3209 // The first window gets a move and the second a down
3210 firstWindow->consumeMotionMove();
3211 secondWindow->consumeMotionDown();
3212
3213 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003214 const bool transferred =
3215 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003216 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3217 ASSERT_FALSE(transferred);
3218 firstWindow->assertNoEvents();
3219 secondWindow->assertNoEvents();
3220
3221 // The rest of the dispatch should proceed as normal
3222 // Send pointer up to the second window
3223 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003224 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003225 {pointInFirst, pointInSecond});
3226 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3227 // The first window gets MOVE and the second gets pointer up
3228 firstWindow->consumeMotionMove();
3229 secondWindow->consumeMotionUp();
3230
3231 // Send up event to the first window
3232 NotifyMotionArgs upMotionArgs =
3233 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3234 ADISPLAY_ID_DEFAULT);
3235 mDispatcher->notifyMotion(&upMotionArgs);
3236 // The first window gets nothing and the second gets up
3237 firstWindow->consumeMotionUp();
3238 secondWindow->assertNoEvents();
3239}
3240
Arthur Hungabbb9d82021-09-01 14:52:30 +00003241// This case will create two windows and one mirrored window on the default display and mirror
3242// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3243// the windows info of second display before default display.
3244TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3246 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003247 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003248 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003249 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003250 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003251 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003252
3253 sp<FakeWindowHandle> mirrorWindowInPrimary =
3254 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3255 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003256
3257 sp<FakeWindowHandle> firstWindowInSecondary =
3258 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3259 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003260
3261 sp<FakeWindowHandle> secondWindowInSecondary =
3262 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3263 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003264
3265 // Update window info, let it find window handle of second display first.
3266 mDispatcher->setInputWindows(
3267 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3268 {ADISPLAY_ID_DEFAULT,
3269 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3270
3271 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3272 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3273 {50, 50}))
3274 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3275
3276 // Window should receive motion event.
3277 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3278
3279 // Transfer touch focus
3280 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3281 secondWindowInPrimary->getToken()));
3282 // The first window gets cancel.
3283 firstWindowInPrimary->consumeMotionCancel();
3284 secondWindowInPrimary->consumeMotionDown();
3285
3286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3287 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3288 ADISPLAY_ID_DEFAULT, {150, 50}))
3289 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3290 firstWindowInPrimary->assertNoEvents();
3291 secondWindowInPrimary->consumeMotionMove();
3292
3293 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3294 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3295 {150, 50}))
3296 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3297 firstWindowInPrimary->assertNoEvents();
3298 secondWindowInPrimary->consumeMotionUp();
3299}
3300
3301// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3302// 'transferTouch' api.
3303TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3305 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003306 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003307 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003308 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003309 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003310 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003311
3312 sp<FakeWindowHandle> mirrorWindowInPrimary =
3313 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3314 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003315
3316 sp<FakeWindowHandle> firstWindowInSecondary =
3317 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3318 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003319
3320 sp<FakeWindowHandle> secondWindowInSecondary =
3321 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3322 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003323
3324 // Update window info, let it find window handle of second display first.
3325 mDispatcher->setInputWindows(
3326 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3327 {ADISPLAY_ID_DEFAULT,
3328 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3329
3330 // Touch on second display.
3331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3332 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3333 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3334
3335 // Window should receive motion event.
3336 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3337
3338 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003339 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003340
3341 // The first window gets cancel.
3342 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3343 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3344
3345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3346 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3347 SECOND_DISPLAY_ID, {150, 50}))
3348 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3349 firstWindowInPrimary->assertNoEvents();
3350 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3351
3352 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3353 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3354 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3355 firstWindowInPrimary->assertNoEvents();
3356 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3357}
3358
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003359TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003360 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003361 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3362 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003363
Vishnu Nair47074b82020-08-14 11:54:47 -07003364 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003366 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003367
3368 window->consumeFocusEvent(true);
3369
3370 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3371 mDispatcher->notifyKey(&keyArgs);
3372
3373 // Window should receive key down event.
3374 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3375}
3376
3377TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003378 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003379 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3380 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003381
Arthur Hung72d8dc32020-03-28 00:48:39 +00003382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003383
3384 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3385 mDispatcher->notifyKey(&keyArgs);
3386 mDispatcher->waitForIdle();
3387
3388 window->assertNoEvents();
3389}
3390
3391// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3392TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003393 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003394 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3395 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003396
Arthur Hung72d8dc32020-03-28 00:48:39 +00003397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003398
3399 // Send key
3400 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3401 mDispatcher->notifyKey(&keyArgs);
3402 // Send motion
3403 NotifyMotionArgs motionArgs =
3404 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3405 ADISPLAY_ID_DEFAULT);
3406 mDispatcher->notifyMotion(&motionArgs);
3407
3408 // Window should receive only the motion event
3409 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3410 window->assertNoEvents(); // Key event or focus event will not be received
3411}
3412
arthurhungea3f4fc2020-12-21 23:18:53 +08003413TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3415
arthurhungea3f4fc2020-12-21 23:18:53 +08003416 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003417 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3418 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003419 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003420
arthurhungea3f4fc2020-12-21 23:18:53 +08003421 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003422 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3423 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003424 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003425
3426 // Add the windows to the dispatcher
3427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3428
3429 PointF pointInFirst = {300, 200};
3430 PointF pointInSecond = {300, 600};
3431
3432 // Send down to the first window
3433 NotifyMotionArgs firstDownMotionArgs =
3434 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3435 ADISPLAY_ID_DEFAULT, {pointInFirst});
3436 mDispatcher->notifyMotion(&firstDownMotionArgs);
3437 // Only the first window should get the down event
3438 firstWindow->consumeMotionDown();
3439 secondWindow->assertNoEvents();
3440
3441 // Send down to the second window
3442 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003443 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003444 {pointInFirst, pointInSecond});
3445 mDispatcher->notifyMotion(&secondDownMotionArgs);
3446 // The first window gets a move and the second a down
3447 firstWindow->consumeMotionMove();
3448 secondWindow->consumeMotionDown();
3449
3450 // Send pointer cancel to the second window
3451 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003452 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003453 {pointInFirst, pointInSecond});
3454 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3455 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3456 // The first window gets move and the second gets cancel.
3457 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3458 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3459
3460 // Send up event.
3461 NotifyMotionArgs upMotionArgs =
3462 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3463 ADISPLAY_ID_DEFAULT);
3464 mDispatcher->notifyMotion(&upMotionArgs);
3465 // The first window gets up and the second gets nothing.
3466 firstWindow->consumeMotionUp();
3467 secondWindow->assertNoEvents();
3468}
3469
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003470TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3471 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3472
3473 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003474 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3476 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3477 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3478 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3479
3480 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3481 window->assertNoEvents();
3482 mDispatcher->waitForIdle();
3483}
3484
chaviwd1c23182019-12-20 18:44:56 -08003485class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003486public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003487 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003488 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003489 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003490 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003491 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003492 }
3493
chaviwd1c23182019-12-20 18:44:56 -08003494 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3495
3496 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3497 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3498 expectedDisplayId, expectedFlags);
3499 }
3500
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003501 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3502
3503 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3504
chaviwd1c23182019-12-20 18:44:56 -08003505 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3506 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3507 expectedDisplayId, expectedFlags);
3508 }
3509
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003510 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3511 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3512 expectedDisplayId, expectedFlags);
3513 }
3514
chaviwd1c23182019-12-20 18:44:56 -08003515 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3516 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3517 expectedDisplayId, expectedFlags);
3518 }
3519
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003520 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3521 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3522 expectedDisplayId, expectedFlags);
3523 }
3524
Arthur Hungfbfa5722021-11-16 02:45:54 +00003525 void consumeMotionPointerDown(int32_t pointerIdx) {
3526 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3527 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3528 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3529 0 /*expectedFlags*/);
3530 }
3531
Evan Rosky84f07f02021-04-16 10:42:42 -07003532 MotionEvent* consumeMotion() {
3533 InputEvent* event = mInputReceiver->consume();
3534 if (!event) {
3535 ADD_FAILURE() << "No event was produced";
3536 return nullptr;
3537 }
3538 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3539 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3540 return nullptr;
3541 }
3542 return static_cast<MotionEvent*>(event);
3543 }
3544
chaviwd1c23182019-12-20 18:44:56 -08003545 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3546
3547private:
3548 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003549};
3550
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003551using InputDispatcherMonitorTest = InputDispatcherTest;
3552
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003553/**
3554 * Two entities that receive touch: A window, and a global monitor.
3555 * The touch goes to the window, and then the window disappears.
3556 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3557 * for the monitor, as well.
3558 * 1. foregroundWindow
3559 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3560 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003561TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3563 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003564 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003565
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003566 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003567
3568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3570 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3571 {100, 200}))
3572 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3573
3574 // Both the foreground window and the global monitor should receive the touch down
3575 window->consumeMotionDown();
3576 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3577
3578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3579 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3580 ADISPLAY_ID_DEFAULT, {110, 200}))
3581 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3582
3583 window->consumeMotionMove();
3584 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3585
3586 // Now the foreground window goes away
3587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3588 window->consumeMotionCancel();
3589 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3590
3591 // If more events come in, there will be no more foreground window to send them to. This will
3592 // cause a cancel for the monitor, as well.
3593 ASSERT_EQ(InputEventInjectionResult::FAILED,
3594 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3595 ADISPLAY_ID_DEFAULT, {120, 200}))
3596 << "Injection should fail because the window was removed";
3597 window->assertNoEvents();
3598 // Global monitor now gets the cancel
3599 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3600}
3601
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003602TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003603 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003604 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3605 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003607
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003608 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003609
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003613 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003614 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003615}
3616
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003617TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3618 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003619
Chris Yea209fde2020-07-22 13:54:51 -07003620 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003621 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3622 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003624
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003626 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003627 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003628 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003629 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003630
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003631 // Pilfer pointers from the monitor.
3632 // This should not do anything and the window should continue to receive events.
3633 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003634
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003636 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3637 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003638 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003639
3640 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3641 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003642}
3643
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003644TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003645 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003646 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3647 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3649 window->setWindowOffset(20, 40);
3650 window->setWindowTransform(0, 1, -1, 0);
3651
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003652 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003653
3654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3655 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3657 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3658 MotionEvent* event = monitor.consumeMotion();
3659 // Even though window has transform, gesture monitor must not.
3660 ASSERT_EQ(ui::Transform(), event->getTransform());
3661}
3662
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003663TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003664 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003665 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003666
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003667 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003668 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003669 << "Injection should fail if there is a monitor, but no touchable window";
3670 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003671}
3672
chaviw81e2bb92019-12-18 15:03:51 -08003673TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003674 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003675 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3676 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003677
Arthur Hung72d8dc32020-03-28 00:48:39 +00003678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003679
3680 NotifyMotionArgs motionArgs =
3681 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3682 ADISPLAY_ID_DEFAULT);
3683
3684 mDispatcher->notifyMotion(&motionArgs);
3685 // Window should receive motion down event.
3686 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3687
3688 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003689 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003690 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3691 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3692 motionArgs.pointerCoords[0].getX() - 10);
3693
3694 mDispatcher->notifyMotion(&motionArgs);
3695 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3696 0 /*expectedFlags*/);
3697}
3698
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003699/**
3700 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3701 * the device default right away. In the test scenario, we check both the default value,
3702 * and the action of enabling / disabling.
3703 */
3704TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003705 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003706 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3707 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003708 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003709
3710 // Set focused application.
3711 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003712 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003713
3714 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003716 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003717 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3718
3719 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003720 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003722 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3723
3724 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003725 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003726 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003727 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003728 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003730 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003731 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3732
3733 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003734 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003736 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3737
3738 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003739 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003740 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003741 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003742 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003744 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003745 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3746
3747 window->assertNoEvents();
3748}
3749
Gang Wange9087892020-01-07 12:17:14 -05003750TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003751 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003752 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3753 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003754
3755 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003756 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003757
Arthur Hung72d8dc32020-03-28 00:48:39 +00003758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003759 setFocusedWindow(window);
3760
Gang Wange9087892020-01-07 12:17:14 -05003761 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3762
3763 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3764 mDispatcher->notifyKey(&keyArgs);
3765
3766 InputEvent* event = window->consume();
3767 ASSERT_NE(event, nullptr);
3768
3769 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3770 ASSERT_NE(verified, nullptr);
3771 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3772
3773 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3774 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3775 ASSERT_EQ(keyArgs.source, verified->source);
3776 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3777
3778 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3779
3780 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003781 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003782 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003783 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3784 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3785 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3786 ASSERT_EQ(0, verifiedKey.repeatCount);
3787}
3788
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003789TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003790 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003791 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3792 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003793
3794 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3795
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003796 ui::Transform transform;
3797 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3798
3799 gui::DisplayInfo displayInfo;
3800 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3801 displayInfo.transform = transform;
3802
3803 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003804
3805 NotifyMotionArgs motionArgs =
3806 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3807 ADISPLAY_ID_DEFAULT);
3808 mDispatcher->notifyMotion(&motionArgs);
3809
3810 InputEvent* event = window->consume();
3811 ASSERT_NE(event, nullptr);
3812
3813 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3814 ASSERT_NE(verified, nullptr);
3815 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3816
3817 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3818 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3819 EXPECT_EQ(motionArgs.source, verified->source);
3820 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3821
3822 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3823
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003824 const vec2 rawXY =
3825 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3826 motionArgs.pointerCoords[0].getXYValue());
3827 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3828 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003829 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003830 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003831 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003832 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3833 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3834}
3835
chaviw09c8d2d2020-08-24 15:48:26 -07003836/**
3837 * Ensure that separate calls to sign the same data are generating the same key.
3838 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3839 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3840 * tests.
3841 */
3842TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3843 KeyEvent event = getTestKeyEvent();
3844 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3845
3846 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3847 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3848 ASSERT_EQ(hmac1, hmac2);
3849}
3850
3851/**
3852 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3853 */
3854TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3855 KeyEvent event = getTestKeyEvent();
3856 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3857 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3858
3859 verifiedEvent.deviceId += 1;
3860 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3861
3862 verifiedEvent.source += 1;
3863 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3864
3865 verifiedEvent.eventTimeNanos += 1;
3866 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3867
3868 verifiedEvent.displayId += 1;
3869 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3870
3871 verifiedEvent.action += 1;
3872 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3873
3874 verifiedEvent.downTimeNanos += 1;
3875 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3876
3877 verifiedEvent.flags += 1;
3878 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3879
3880 verifiedEvent.keyCode += 1;
3881 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3882
3883 verifiedEvent.scanCode += 1;
3884 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3885
3886 verifiedEvent.metaState += 1;
3887 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3888
3889 verifiedEvent.repeatCount += 1;
3890 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3891}
3892
Vishnu Nair958da932020-08-21 17:12:37 -07003893TEST_F(InputDispatcherTest, SetFocusedWindow) {
3894 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3895 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003896 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003897 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003898 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003899 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3900
3901 // Top window is also focusable but is not granted focus.
3902 windowTop->setFocusable(true);
3903 windowSecond->setFocusable(true);
3904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3905 setFocusedWindow(windowSecond);
3906
3907 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3909 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003910
3911 // Focused window should receive event.
3912 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3913 windowTop->assertNoEvents();
3914}
3915
3916TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3917 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3918 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003919 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003920 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3921
3922 window->setFocusable(true);
3923 // Release channel for window is no longer valid.
3924 window->releaseChannel();
3925 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3926 setFocusedWindow(window);
3927
3928 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003929 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3930 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003931
3932 // window channel is invalid, so it should not receive any input event.
3933 window->assertNoEvents();
3934}
3935
3936TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3938 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003939 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003940 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003941 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3942
Vishnu Nair958da932020-08-21 17:12:37 -07003943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3944 setFocusedWindow(window);
3945
3946 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003947 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3948 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003949
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003950 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003951 window->assertNoEvents();
3952}
3953
3954TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3956 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003957 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003958 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003959 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003960 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3961
3962 windowTop->setFocusable(true);
3963 windowSecond->setFocusable(true);
3964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3965 setFocusedWindow(windowTop);
3966 windowTop->consumeFocusEvent(true);
3967
3968 setFocusedWindow(windowSecond, windowTop);
3969 windowSecond->consumeFocusEvent(true);
3970 windowTop->consumeFocusEvent(false);
3971
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3973 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003974
3975 // Focused window should receive event.
3976 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3977}
3978
3979TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3980 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3981 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003982 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003983 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003984 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003985 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3986
3987 windowTop->setFocusable(true);
3988 windowSecond->setFocusable(true);
3989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3990 setFocusedWindow(windowSecond, windowTop);
3991
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003992 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3993 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003994
3995 // Event should be dropped.
3996 windowTop->assertNoEvents();
3997 windowSecond->assertNoEvents();
3998}
3999
4000TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
4001 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4002 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004003 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004004 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004005 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
4006 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004007 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4008
4009 window->setFocusable(true);
4010 previousFocusedWindow->setFocusable(true);
4011 window->setVisible(false);
4012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
4013 setFocusedWindow(previousFocusedWindow);
4014 previousFocusedWindow->consumeFocusEvent(true);
4015
4016 // Requesting focus on invisible window takes focus from currently focused window.
4017 setFocusedWindow(window);
4018 previousFocusedWindow->consumeFocusEvent(false);
4019
4020 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004022 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004023 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004024
4025 // Window does not get focus event or key down.
4026 window->assertNoEvents();
4027
4028 // Window becomes visible.
4029 window->setVisible(true);
4030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4031
4032 // Window receives focus event.
4033 window->consumeFocusEvent(true);
4034 // Focused window receives key down.
4035 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4036}
4037
Vishnu Nair599f1412021-06-21 10:39:58 -07004038TEST_F(InputDispatcherTest, DisplayRemoved) {
4039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4040 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004041 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07004042 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4043
4044 // window is granted focus.
4045 window->setFocusable(true);
4046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4047 setFocusedWindow(window);
4048 window->consumeFocusEvent(true);
4049
4050 // When a display is removed window loses focus.
4051 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
4052 window->consumeFocusEvent(false);
4053}
4054
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004055/**
4056 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
4057 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
4058 * of the 'slipperyEnterWindow'.
4059 *
4060 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
4061 * a way so that the touched location is no longer covered by the top window.
4062 *
4063 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
4064 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
4065 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
4066 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
4067 * with ACTION_DOWN).
4068 * Thus, the touch has been transferred from the top window into the bottom window, because the top
4069 * window moved itself away from the touched location and had Flag::SLIPPERY.
4070 *
4071 * Even though the top window moved away from the touched location, it is still obscuring the bottom
4072 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
4073 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
4074 *
4075 * In this test, we ensure that the event received by the bottom window has
4076 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
4077 */
4078TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004079 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
4080 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004081
4082 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4084
4085 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004086 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004087 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004088 // Make sure this one overlaps the bottom window
4089 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
4090 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
4091 // one. Windows with the same owner are not considered to be occluding each other.
4092 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
4093
4094 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004095 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004096 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
4097
4098 mDispatcher->setInputWindows(
4099 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4100
4101 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
4102 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4103 ADISPLAY_ID_DEFAULT, {{50, 50}});
4104 mDispatcher->notifyMotion(&args);
4105 slipperyExitWindow->consumeMotionDown();
4106 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
4107 mDispatcher->setInputWindows(
4108 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4109
4110 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4111 ADISPLAY_ID_DEFAULT, {{51, 51}});
4112 mDispatcher->notifyMotion(&args);
4113
4114 slipperyExitWindow->consumeMotionCancel();
4115
4116 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
4117 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
4118}
4119
Garfield Tan1c7bc862020-01-28 13:24:04 -08004120class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
4121protected:
4122 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
4123 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
4124
Chris Yea209fde2020-07-22 13:54:51 -07004125 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004126 sp<FakeWindowHandle> mWindow;
4127
4128 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004129 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08004130 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004131 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004132 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
4133 ASSERT_EQ(OK, mDispatcher->start());
4134
4135 setUpWindow();
4136 }
4137
4138 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07004139 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004140 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004141
Vishnu Nair47074b82020-08-14 11:54:47 -07004142 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004144 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004145 mWindow->consumeFocusEvent(true);
4146 }
4147
Chris Ye2ad95392020-09-01 13:44:44 -07004148 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004149 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004150 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004151 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
4152 mDispatcher->notifyKey(&keyArgs);
4153
4154 // Window should receive key down event.
4155 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4156 }
4157
4158 void expectKeyRepeatOnce(int32_t repeatCount) {
4159 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
4160 InputEvent* repeatEvent = mWindow->consume();
4161 ASSERT_NE(nullptr, repeatEvent);
4162
4163 uint32_t eventType = repeatEvent->getType();
4164 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4165
4166 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4167 uint32_t eventAction = repeatKeyEvent->getAction();
4168 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4169 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4170 }
4171
Chris Ye2ad95392020-09-01 13:44:44 -07004172 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004173 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004174 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004175 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4176 mDispatcher->notifyKey(&keyArgs);
4177
4178 // Window should receive key down event.
4179 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
4180 0 /*expectedFlags*/);
4181 }
4182};
4183
4184TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07004185 sendAndConsumeKeyDown(1 /* deviceId */);
4186 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4187 expectKeyRepeatOnce(repeatCount);
4188 }
4189}
4190
4191TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
4192 sendAndConsumeKeyDown(1 /* deviceId */);
4193 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4194 expectKeyRepeatOnce(repeatCount);
4195 }
4196 sendAndConsumeKeyDown(2 /* deviceId */);
4197 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004198 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4199 expectKeyRepeatOnce(repeatCount);
4200 }
4201}
4202
4203TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07004204 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004205 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07004206 sendAndConsumeKeyUp(1 /* deviceId */);
4207 mWindow->assertNoEvents();
4208}
4209
4210TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
4211 sendAndConsumeKeyDown(1 /* deviceId */);
4212 expectKeyRepeatOnce(1 /*repeatCount*/);
4213 sendAndConsumeKeyDown(2 /* deviceId */);
4214 expectKeyRepeatOnce(1 /*repeatCount*/);
4215 // Stale key up from device 1.
4216 sendAndConsumeKeyUp(1 /* deviceId */);
4217 // Device 2 is still down, keep repeating
4218 expectKeyRepeatOnce(2 /*repeatCount*/);
4219 expectKeyRepeatOnce(3 /*repeatCount*/);
4220 // Device 2 key up
4221 sendAndConsumeKeyUp(2 /* deviceId */);
4222 mWindow->assertNoEvents();
4223}
4224
4225TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
4226 sendAndConsumeKeyDown(1 /* deviceId */);
4227 expectKeyRepeatOnce(1 /*repeatCount*/);
4228 sendAndConsumeKeyDown(2 /* deviceId */);
4229 expectKeyRepeatOnce(1 /*repeatCount*/);
4230 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
4231 sendAndConsumeKeyUp(2 /* deviceId */);
4232 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004233 mWindow->assertNoEvents();
4234}
4235
liushenxiang42232912021-05-21 20:24:09 +08004236TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4237 sendAndConsumeKeyDown(DEVICE_ID);
4238 expectKeyRepeatOnce(1 /*repeatCount*/);
4239 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
4240 mDispatcher->notifyDeviceReset(&args);
4241 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4242 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4243 mWindow->assertNoEvents();
4244}
4245
Garfield Tan1c7bc862020-01-28 13:24:04 -08004246TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004247 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004248 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4249 InputEvent* repeatEvent = mWindow->consume();
4250 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4251 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4252 IdGenerator::getSource(repeatEvent->getId()));
4253 }
4254}
4255
4256TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004257 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004258
4259 std::unordered_set<int32_t> idSet;
4260 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4261 InputEvent* repeatEvent = mWindow->consume();
4262 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4263 int32_t id = repeatEvent->getId();
4264 EXPECT_EQ(idSet.end(), idSet.find(id));
4265 idSet.insert(id);
4266 }
4267}
4268
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004269/* Test InputDispatcher for MultiDisplay */
4270class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4271public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004272 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004273 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004274
Chris Yea209fde2020-07-22 13:54:51 -07004275 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004276 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004277 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004278
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004279 // Set focus window for primary display, but focused display would be second one.
4280 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004281 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004283 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004284 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004285
Chris Yea209fde2020-07-22 13:54:51 -07004286 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004287 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004288 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004289 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004290 // Set focus display to second one.
4291 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4292 // Set focus window for second display.
4293 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004294 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004295 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004296 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004297 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004298 }
4299
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004300 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004301 InputDispatcherTest::TearDown();
4302
Chris Yea209fde2020-07-22 13:54:51 -07004303 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004304 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004305 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004306 windowInSecondary.clear();
4307 }
4308
4309protected:
Chris Yea209fde2020-07-22 13:54:51 -07004310 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004311 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004312 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004313 sp<FakeWindowHandle> windowInSecondary;
4314};
4315
4316TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4317 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004318 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4319 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4320 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004321 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004322 windowInSecondary->assertNoEvents();
4323
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004324 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4326 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4327 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004328 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004329 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004330}
4331
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004332TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004333 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4335 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004337 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004338 windowInSecondary->assertNoEvents();
4339
4340 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004343 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004344 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004345
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004346 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004347 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004349 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004350 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4351 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004352
4353 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004354 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004356 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004357 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004358 windowInSecondary->assertNoEvents();
4359}
4360
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004361// Test per-display input monitors for motion event.
4362TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004363 FakeMonitorReceiver monitorInPrimary =
4364 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4365 FakeMonitorReceiver monitorInSecondary =
4366 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004367
4368 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4370 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4371 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004372 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004373 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004374 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004375 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004376
4377 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4379 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4380 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004381 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004382 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004383 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004384 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004385
4386 // Test inject a non-pointer motion event.
4387 // If specific a display, it will dispatch to the focused window of particular display,
4388 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4390 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4391 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004392 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004393 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004394 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004395 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004396}
4397
4398// Test per-display input monitors for key event.
4399TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004400 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004401 FakeMonitorReceiver monitorInPrimary =
4402 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4403 FakeMonitorReceiver monitorInSecondary =
4404 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004405
4406 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4408 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004409 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004410 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004411 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004412 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004413}
4414
Vishnu Nair958da932020-08-21 17:12:37 -07004415TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4416 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004417 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004418 secondWindowInPrimary->setFocusable(true);
4419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4420 setFocusedWindow(secondWindowInPrimary);
4421 windowInPrimary->consumeFocusEvent(false);
4422 secondWindowInPrimary->consumeFocusEvent(true);
4423
4424 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4426 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004427 windowInPrimary->assertNoEvents();
4428 windowInSecondary->assertNoEvents();
4429 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4430}
4431
Arthur Hungdfd528e2021-12-08 13:23:04 +00004432TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4433 FakeMonitorReceiver monitorInPrimary =
4434 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4435 FakeMonitorReceiver monitorInSecondary =
4436 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4437
4438 // Test touch down on primary display.
4439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4440 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4441 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4442 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4443 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4444
4445 // Test touch down on second display.
4446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4447 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4448 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4449 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4450 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4451
4452 // Trigger cancel touch.
4453 mDispatcher->cancelCurrentTouch();
4454 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4455 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4456 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4457 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4458
4459 // Test inject a move motion event, no window/monitor should receive the event.
4460 ASSERT_EQ(InputEventInjectionResult::FAILED,
4461 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4462 ADISPLAY_ID_DEFAULT, {110, 200}))
4463 << "Inject motion event should return InputEventInjectionResult::FAILED";
4464 windowInPrimary->assertNoEvents();
4465 monitorInPrimary.assertNoEvents();
4466
4467 ASSERT_EQ(InputEventInjectionResult::FAILED,
4468 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4469 SECOND_DISPLAY_ID, {110, 200}))
4470 << "Inject motion event should return InputEventInjectionResult::FAILED";
4471 windowInSecondary->assertNoEvents();
4472 monitorInSecondary.assertNoEvents();
4473}
4474
Jackal Guof9696682018-10-05 12:23:23 +08004475class InputFilterTest : public InputDispatcherTest {
4476protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004477 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4478 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004479 NotifyMotionArgs motionArgs;
4480
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004481 motionArgs =
4482 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004483 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004484 motionArgs =
4485 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004486 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004487 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004488 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004489 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4490 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004491 } else {
4492 mFakePolicy->assertFilterInputEventWasNotCalled();
4493 }
4494 }
4495
4496 void testNotifyKey(bool expectToBeFiltered) {
4497 NotifyKeyArgs keyArgs;
4498
4499 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4500 mDispatcher->notifyKey(&keyArgs);
4501 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4502 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004503 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004504
4505 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004506 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004507 } else {
4508 mFakePolicy->assertFilterInputEventWasNotCalled();
4509 }
4510 }
4511};
4512
4513// Test InputFilter for MotionEvent
4514TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4515 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4516 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4517 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4518
4519 // Enable InputFilter
4520 mDispatcher->setInputFilterEnabled(true);
4521 // Test touch on both primary and second display, and check if both events are filtered.
4522 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4523 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4524
4525 // Disable InputFilter
4526 mDispatcher->setInputFilterEnabled(false);
4527 // Test touch on both primary and second display, and check if both events aren't filtered.
4528 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4529 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4530}
4531
4532// Test InputFilter for KeyEvent
4533TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4534 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4535 testNotifyKey(/*expectToBeFiltered*/ false);
4536
4537 // Enable InputFilter
4538 mDispatcher->setInputFilterEnabled(true);
4539 // Send a key event, and check if it is filtered.
4540 testNotifyKey(/*expectToBeFiltered*/ true);
4541
4542 // Disable InputFilter
4543 mDispatcher->setInputFilterEnabled(false);
4544 // Send a key event, and check if it isn't filtered.
4545 testNotifyKey(/*expectToBeFiltered*/ false);
4546}
4547
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004548// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4549// logical display coordinate space.
4550TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4551 ui::Transform firstDisplayTransform;
4552 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4553 ui::Transform secondDisplayTransform;
4554 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4555
4556 std::vector<gui::DisplayInfo> displayInfos(2);
4557 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4558 displayInfos[0].transform = firstDisplayTransform;
4559 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4560 displayInfos[1].transform = secondDisplayTransform;
4561
4562 mDispatcher->onWindowInfosChanged({}, displayInfos);
4563
4564 // Enable InputFilter
4565 mDispatcher->setInputFilterEnabled(true);
4566
4567 // Ensure the correct transforms are used for the displays.
4568 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4569 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4570}
4571
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004572class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4573protected:
4574 virtual void SetUp() override {
4575 InputDispatcherTest::SetUp();
4576
4577 /**
4578 * We don't need to enable input filter to test the injected event policy, but we enabled it
4579 * here to make the tests more realistic, since this policy only matters when inputfilter is
4580 * on.
4581 */
4582 mDispatcher->setInputFilterEnabled(true);
4583
4584 std::shared_ptr<InputApplicationHandle> application =
4585 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004586 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4587 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004588
4589 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4590 mWindow->setFocusable(true);
4591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4592 setFocusedWindow(mWindow);
4593 mWindow->consumeFocusEvent(true);
4594 }
4595
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004596 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4597 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598 KeyEvent event;
4599
4600 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4601 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4602 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4603 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4604 const int32_t additionalPolicyFlags =
4605 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004607 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004608 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4609 policyFlags | additionalPolicyFlags));
4610
4611 InputEvent* received = mWindow->consume();
4612 ASSERT_NE(nullptr, received);
4613 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004614 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4615 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4616 ASSERT_EQ(flags, keyEvent.getFlags());
4617 }
4618
4619 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4620 int32_t flags) {
4621 MotionEvent event;
4622 PointerProperties pointerProperties[1];
4623 PointerCoords pointerCoords[1];
4624 pointerProperties[0].clear();
4625 pointerProperties[0].id = 0;
4626 pointerCoords[0].clear();
4627 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4628 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4629
4630 ui::Transform identityTransform;
4631 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4632 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4633 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4634 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4635 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004636 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004637 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004638 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4639
4640 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004642 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004643 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4644 policyFlags | additionalPolicyFlags));
4645
4646 InputEvent* received = mWindow->consume();
4647 ASSERT_NE(nullptr, received);
4648 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4649 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4650 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4651 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004652 }
4653
4654private:
4655 sp<FakeWindowHandle> mWindow;
4656};
4657
4658TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004659 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4660 // filter. Without it, the event will no different from a regularly injected event, and the
4661 // injected device id will be overwritten.
4662 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4663 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004664}
4665
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004666TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004667 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004668 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4669 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4670}
4671
4672TEST_F(InputFilterInjectionPolicyTest,
4673 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4674 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4675 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4676 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004677}
4678
4679TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4680 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004681 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004682}
4683
chaviwfd6d3512019-03-25 13:23:49 -07004684class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004685 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004686 InputDispatcherTest::SetUp();
4687
Chris Yea209fde2020-07-22 13:54:51 -07004688 std::shared_ptr<FakeApplicationHandle> application =
4689 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004690 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004691 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004692 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004693
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004694 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004695 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004696 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004697
4698 // Set focused application.
4699 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004700 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004701
4702 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004704 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004705 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004706 }
4707
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004708 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004709 InputDispatcherTest::TearDown();
4710
4711 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004712 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004713 }
4714
4715protected:
4716 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004717 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004718 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004719};
4720
4721// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4722// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4723// the onPointerDownOutsideFocus callback.
4724TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4727 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004729 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004730
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004731 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004732 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4733}
4734
4735// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4736// DOWN on the window that doesn't have focus. Ensure no window received the
4737// onPointerDownOutsideFocus callback.
4738TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004740 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004742 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004743
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004744 ASSERT_TRUE(mDispatcher->waitForIdle());
4745 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004746}
4747
4748// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4749// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4750TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4752 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004754 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004755
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004756 ASSERT_TRUE(mDispatcher->waitForIdle());
4757 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004758}
4759
4760// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4761// DOWN on the window that already has focus. Ensure no window received the
4762// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004763TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004766 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004768 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004769
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004770 ASSERT_TRUE(mDispatcher->waitForIdle());
4771 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004772}
4773
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004774// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4775// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4776TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4777 const MotionEvent event =
4778 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4779 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4780 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4781 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4782 .build();
4783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4784 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4785 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4786
4787 ASSERT_TRUE(mDispatcher->waitForIdle());
4788 mFakePolicy->assertOnPointerDownWasNotCalled();
4789 // Ensure that the unfocused window did not receive any FOCUS events.
4790 mUnfocusedWindow->assertNoEvents();
4791}
4792
chaviwaf87b3e2019-10-01 16:59:28 -07004793// These tests ensures we can send touch events to a single client when there are multiple input
4794// windows that point to the same client token.
4795class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4796 virtual void SetUp() override {
4797 InputDispatcherTest::SetUp();
4798
Chris Yea209fde2020-07-22 13:54:51 -07004799 std::shared_ptr<FakeApplicationHandle> application =
4800 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004801 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4802 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004803 mWindow1->setFrame(Rect(0, 0, 100, 100));
4804
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004805 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4806 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004807 mWindow2->setFrame(Rect(100, 100, 200, 200));
4808
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004810 }
4811
4812protected:
4813 sp<FakeWindowHandle> mWindow1;
4814 sp<FakeWindowHandle> mWindow2;
4815
4816 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004817 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004818 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4819 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004820 }
4821
4822 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4823 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004824 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004825 InputEvent* event = window->consume();
4826
4827 ASSERT_NE(nullptr, event) << name.c_str()
4828 << ": consumer should have returned non-NULL event.";
4829
4830 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4831 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4832 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4833
4834 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004835 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08004836 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07004837
4838 for (size_t i = 0; i < points.size(); i++) {
4839 float expectedX = points[i].x;
4840 float expectedY = points[i].y;
4841
4842 EXPECT_EQ(expectedX, motionEvent.getX(i))
4843 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4844 << ", got " << motionEvent.getX(i);
4845 EXPECT_EQ(expectedY, motionEvent.getY(i))
4846 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4847 << ", got " << motionEvent.getY(i);
4848 }
4849 }
chaviw9eaa22c2020-07-01 16:21:27 -07004850
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004851 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004852 std::vector<PointF> expectedPoints) {
4853 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4854 ADISPLAY_ID_DEFAULT, touchedPoints);
4855 mDispatcher->notifyMotion(&motionArgs);
4856
4857 // Always consume from window1 since it's the window that has the InputReceiver
4858 consumeMotionEvent(mWindow1, action, expectedPoints);
4859 }
chaviwaf87b3e2019-10-01 16:59:28 -07004860};
4861
4862TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4863 // Touch Window 1
4864 PointF touchedPoint = {10, 10};
4865 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004866 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004867
4868 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004869 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004870
4871 // Touch Window 2
4872 touchedPoint = {150, 150};
4873 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004874 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004875}
4876
chaviw9eaa22c2020-07-01 16:21:27 -07004877TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4878 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004879 mWindow2->setWindowScale(0.5f, 0.5f);
4880
4881 // Touch Window 1
4882 PointF touchedPoint = {10, 10};
4883 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004884 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004885 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004886 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004887
4888 // Touch Window 2
4889 touchedPoint = {150, 150};
4890 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004891 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4892 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004893
chaviw9eaa22c2020-07-01 16:21:27 -07004894 // Update the transform so rotation is set
4895 mWindow2->setWindowTransform(0, -1, 1, 0);
4896 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4897 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004898}
4899
chaviw9eaa22c2020-07-01 16:21:27 -07004900TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004901 mWindow2->setWindowScale(0.5f, 0.5f);
4902
4903 // Touch Window 1
4904 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4905 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004906 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004907
4908 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004909 touchedPoints.push_back(PointF{150, 150});
4910 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004911 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004912
chaviw9eaa22c2020-07-01 16:21:27 -07004913 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004914 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004915 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004916
chaviw9eaa22c2020-07-01 16:21:27 -07004917 // Update the transform so rotation is set for Window 2
4918 mWindow2->setWindowTransform(0, -1, 1, 0);
4919 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004920 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004921}
4922
chaviw9eaa22c2020-07-01 16:21:27 -07004923TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004924 mWindow2->setWindowScale(0.5f, 0.5f);
4925
4926 // Touch Window 1
4927 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4928 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004929 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004930
4931 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004932 touchedPoints.push_back(PointF{150, 150});
4933 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004934
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004935 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004936
4937 // Move both windows
4938 touchedPoints = {{20, 20}, {175, 175}};
4939 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4940 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4941
chaviw9eaa22c2020-07-01 16:21:27 -07004942 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004943
chaviw9eaa22c2020-07-01 16:21:27 -07004944 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004945 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004946 expectedPoints.pop_back();
4947
4948 // Touch Window 2
4949 mWindow2->setWindowTransform(0, -1, 1, 0);
4950 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004951 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004952
4953 // Move both windows
4954 touchedPoints = {{20, 20}, {175, 175}};
4955 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4956 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4957
4958 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004959}
4960
4961TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4962 mWindow1->setWindowScale(0.5f, 0.5f);
4963
4964 // Touch Window 1
4965 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4966 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004967 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004968
4969 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004970 touchedPoints.push_back(PointF{150, 150});
4971 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004972
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004973 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004974
4975 // Move both windows
4976 touchedPoints = {{20, 20}, {175, 175}};
4977 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4978 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4979
chaviw9eaa22c2020-07-01 16:21:27 -07004980 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004981}
4982
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004983class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4984 virtual void SetUp() override {
4985 InputDispatcherTest::SetUp();
4986
Chris Yea209fde2020-07-22 13:54:51 -07004987 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004988 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004989 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4990 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004991 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004992 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004993 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004994
4995 // Set focused application.
4996 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4997
4998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004999 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005000 mWindow->consumeFocusEvent(true);
5001 }
5002
5003 virtual void TearDown() override {
5004 InputDispatcherTest::TearDown();
5005 mWindow.clear();
5006 }
5007
5008protected:
Chris Yea209fde2020-07-22 13:54:51 -07005009 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005010 sp<FakeWindowHandle> mWindow;
5011 static constexpr PointF WINDOW_LOCATION = {20, 20};
5012
5013 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5016 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005018 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5019 WINDOW_LOCATION));
5020 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005021
5022 sp<FakeWindowHandle> addSpyWindow() {
5023 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005024 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005025 spy->setTrustedOverlay(true);
5026 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005027 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005028 spy->setDispatchingTimeout(30ms);
5029 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
5030 return spy;
5031 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005032};
5033
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005034// Send a tap and respond, which should not cause an ANR.
5035TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
5036 tapOnWindow();
5037 mWindow->consumeMotionDown();
5038 mWindow->consumeMotionUp();
5039 ASSERT_TRUE(mDispatcher->waitForIdle());
5040 mFakePolicy->assertNotifyAnrWasNotCalled();
5041}
5042
5043// Send a regular key and respond, which should not cause an ANR.
5044TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005046 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5047 ASSERT_TRUE(mDispatcher->waitForIdle());
5048 mFakePolicy->assertNotifyAnrWasNotCalled();
5049}
5050
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005051TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
5052 mWindow->setFocusable(false);
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5054 mWindow->consumeFocusEvent(false);
5055
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005056 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005057 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005058 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5059 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005061 // Key will not go to window because we have no focused window.
5062 // The 'no focused window' ANR timer should start instead.
5063
5064 // Now, the focused application goes away.
5065 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
5066 // The key should get dropped and there should be no ANR.
5067
5068 ASSERT_TRUE(mDispatcher->waitForIdle());
5069 mFakePolicy->assertNotifyAnrWasNotCalled();
5070}
5071
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005072// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005073// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
5074// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005075TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005077 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5078 WINDOW_LOCATION));
5079
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005080 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
5081 ASSERT_TRUE(sequenceNum);
5082 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005083 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005084
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 mWindow->finishEvent(*sequenceNum);
5086 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5087 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005088 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005089 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005090}
5091
5092// Send a key to the app and have the app not respond right away.
5093TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
5094 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005096 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
5097 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005098 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005099 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005100 ASSERT_TRUE(mDispatcher->waitForIdle());
5101}
5102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005103// We have a focused application, but no focused window
5104TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005105 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5107 mWindow->consumeFocusEvent(false);
5108
5109 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005110 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005111 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5112 WINDOW_LOCATION));
5113 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
5114 mDispatcher->waitForIdle();
5115 mFakePolicy->assertNotifyAnrWasNotCalled();
5116
5117 // Once a focused event arrives, we get an ANR for this application
5118 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5119 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005120 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005122 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005123 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005124 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07005125 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005126 ASSERT_TRUE(mDispatcher->waitForIdle());
5127}
5128
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005129/**
5130 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
5131 * there will not be an ANR.
5132 */
5133TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
5134 mWindow->setFocusable(false);
5135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5136 mWindow->consumeFocusEvent(false);
5137
5138 KeyEvent event;
5139 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
5140 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
5141
5142 // Define a valid key down event that is stale (too old).
5143 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
5144 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
5145 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
5146
5147 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
5148
5149 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00005150 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005151 InputEventInjectionSync::WAIT_FOR_RESULT,
5152 INJECT_EVENT_TIMEOUT, policyFlags);
5153 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
5154 << "Injection should fail because the event is stale";
5155
5156 ASSERT_TRUE(mDispatcher->waitForIdle());
5157 mFakePolicy->assertNotifyAnrWasNotCalled();
5158 mWindow->assertNoEvents();
5159}
5160
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005161// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005162// Make sure that we don't notify policy twice about the same ANR.
5163TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005164 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5166 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005167
5168 // Once a focused event arrives, we get an ANR for this application
5169 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5170 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005171 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005172 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005173 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005174 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005175 const std::chrono::duration appTimeout =
5176 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5177 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005178
Vishnu Naire4df8752022-09-08 09:17:55 -07005179 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005180 // ANR should not be raised again. It is up to policy to do that if it desires.
5181 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005182
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005183 // If we now get a focused window, the ANR should stop, but the policy handles that via
5184 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005185 ASSERT_TRUE(mDispatcher->waitForIdle());
5186}
5187
5188// We have a focused application, but no focused window
5189TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005190 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5192 mWindow->consumeFocusEvent(false);
5193
5194 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005195 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005197 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5198 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199
Vishnu Naire4df8752022-09-08 09:17:55 -07005200 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5201 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202
5203 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005204 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005205 ASSERT_TRUE(mDispatcher->waitForIdle());
5206 mWindow->assertNoEvents();
5207}
5208
5209/**
5210 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5211 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5212 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5213 * the ANR mechanism should still work.
5214 *
5215 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5216 * DOWN event, while not responding on the second one.
5217 */
5218TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5219 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5220 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5221 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5222 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5223 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005224 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225
5226 // Now send ACTION_UP, with identical timestamp
5227 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5228 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5229 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5230 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005231 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005232
5233 // We have now sent down and up. Let's consume first event and then ANR on the second.
5234 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5235 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005236 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237}
5238
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005239// A spy window can receive an ANR
5240TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5241 sp<FakeWindowHandle> spy = addSpyWindow();
5242
5243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5244 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5245 WINDOW_LOCATION));
5246 mWindow->consumeMotionDown();
5247
5248 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5249 ASSERT_TRUE(sequenceNum);
5250 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005251 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005252
5253 spy->finishEvent(*sequenceNum);
5254 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
5255 0 /*flags*/);
5256 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005257 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005258}
5259
5260// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005261// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005262TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5263 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5266 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005267 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005269
5270 // Stuck on the ACTION_UP
5271 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005272 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005273
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005274 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005275 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005276 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5277 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005278
5279 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5280 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005281 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005282 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005283 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005284}
5285
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005286// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005287// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005288TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5289 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005290
5291 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005292 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5293 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005294
5295 mWindow->consumeMotionDown();
5296 // Stuck on the ACTION_UP
5297 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005298 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005299
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005300 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005301 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005302 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5303 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005304
5305 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5306 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005307 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005308 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005309 spy->assertNoEvents();
5310}
5311
5312TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5313 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5314
5315 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5316
5317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5318 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5319 WINDOW_LOCATION));
5320
5321 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5322 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5323 ASSERT_TRUE(consumeSeq);
5324
Prabir Pradhanedd96402022-02-15 01:46:16 -08005325 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005326
5327 monitor.finishEvent(*consumeSeq);
5328 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5329
5330 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005331 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005332}
5333
5334// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5335// process events, you don't get an anr. When the window later becomes unresponsive again, you
5336// get an ANR again.
5337// 1. tap -> block on ACTION_UP -> receive ANR
5338// 2. consume all pending events (= queue becomes healthy again)
5339// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5340TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5341 tapOnWindow();
5342
5343 mWindow->consumeMotionDown();
5344 // Block on ACTION_UP
5345 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005346 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005347 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5348 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005349 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005350 mWindow->assertNoEvents();
5351
5352 tapOnWindow();
5353 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005354 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005355 mWindow->consumeMotionUp();
5356
5357 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005358 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005359 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005360 mWindow->assertNoEvents();
5361}
5362
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005363// If a connection remains unresponsive for a while, make sure policy is only notified once about
5364// it.
5365TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005367 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5368 WINDOW_LOCATION));
5369
5370 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005371 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005372 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005373 // 'notifyConnectionUnresponsive' should only be called once per connection
5374 mFakePolicy->assertNotifyAnrWasNotCalled();
5375 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376 mWindow->consumeMotionDown();
5377 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5378 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5379 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005380 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005381 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005382 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005383}
5384
5385/**
5386 * If a window is processing a motion event, and then a key event comes in, the key event should
5387 * not to to the focused window until the motion is processed.
5388 *
5389 * Warning!!!
5390 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5391 * and the injection timeout that we specify when injecting the key.
5392 * We must have the injection timeout (10ms) be smaller than
5393 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5394 *
5395 * If that value changes, this test should also change.
5396 */
5397TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5398 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5400
5401 tapOnWindow();
5402 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5403 ASSERT_TRUE(downSequenceNum);
5404 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5405 ASSERT_TRUE(upSequenceNum);
5406 // Don't finish the events yet, and send a key
5407 // Injection will "succeed" because we will eventually give up and send the key to the focused
5408 // window even if motions are still being processed. But because the injection timeout is short,
5409 // we will receive INJECTION_TIMED_OUT as the result.
5410
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005411 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005412 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005413 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5414 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 // Key will not be sent to the window, yet, because the window is still processing events
5416 // and the key remains pending, waiting for the touch events to be processed
5417 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5418 ASSERT_FALSE(keySequenceNum);
5419
5420 std::this_thread::sleep_for(500ms);
5421 // if we wait long enough though, dispatcher will give up, and still send the key
5422 // to the focused window, even though we have not yet finished the motion event
5423 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5424 mWindow->finishEvent(*downSequenceNum);
5425 mWindow->finishEvent(*upSequenceNum);
5426}
5427
5428/**
5429 * If a window is processing a motion event, and then a key event comes in, the key event should
5430 * not go to the focused window until the motion is processed.
5431 * If then a new motion comes in, then the pending key event should be going to the currently
5432 * focused window right away.
5433 */
5434TEST_F(InputDispatcherSingleWindowAnr,
5435 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5436 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5438
5439 tapOnWindow();
5440 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5441 ASSERT_TRUE(downSequenceNum);
5442 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5443 ASSERT_TRUE(upSequenceNum);
5444 // Don't finish the events yet, and send a key
5445 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005447 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005448 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005449 // At this point, key is still pending, and should not be sent to the application yet.
5450 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5451 ASSERT_FALSE(keySequenceNum);
5452
5453 // Now tap down again. It should cause the pending key to go to the focused window right away.
5454 tapOnWindow();
5455 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5456 // the other events yet. We can finish events in any order.
5457 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5458 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5459 mWindow->consumeMotionDown();
5460 mWindow->consumeMotionUp();
5461 mWindow->assertNoEvents();
5462}
5463
5464class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5465 virtual void SetUp() override {
5466 InputDispatcherTest::SetUp();
5467
Chris Yea209fde2020-07-22 13:54:51 -07005468 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005469 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005470 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5471 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005472 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005473 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005474 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005475
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005476 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5477 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005478 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005479 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005480
5481 // Set focused application.
5482 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005483 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005484
5485 // Expect one focus window exist in display.
5486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005487 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 mFocusedWindow->consumeFocusEvent(true);
5489 }
5490
5491 virtual void TearDown() override {
5492 InputDispatcherTest::TearDown();
5493
5494 mUnfocusedWindow.clear();
5495 mFocusedWindow.clear();
5496 }
5497
5498protected:
Chris Yea209fde2020-07-22 13:54:51 -07005499 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005500 sp<FakeWindowHandle> mUnfocusedWindow;
5501 sp<FakeWindowHandle> mFocusedWindow;
5502 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5503 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5504 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5505
5506 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5507
5508 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5509
5510private:
5511 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005513 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5514 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005516 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5517 location));
5518 }
5519};
5520
5521// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5522// should be ANR'd first.
5523TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005525 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5526 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005527 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 mFocusedWindow->consumeMotionDown();
5529 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5530 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5531 // We consumed all events, so no ANR
5532 ASSERT_TRUE(mDispatcher->waitForIdle());
5533 mFakePolicy->assertNotifyAnrWasNotCalled();
5534
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005535 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005536 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5537 FOCUSED_WINDOW_LOCATION));
5538 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5539 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005540
5541 const std::chrono::duration timeout =
5542 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005543 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005544 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5545 // sequence to make it consistent
5546 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005548 mFocusedWindow->consumeMotionDown();
5549 // This cancel is generated because the connection was unresponsive
5550 mFocusedWindow->consumeMotionCancel();
5551 mFocusedWindow->assertNoEvents();
5552 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005553 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005554 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5555 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005556 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557}
5558
5559// If we have 2 windows with identical timeouts that are both unresponsive,
5560// it doesn't matter which order they should have ANR.
5561// But we should receive ANR for both.
5562TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5563 // Set the timeout for unfocused window to match the focused window
5564 mUnfocusedWindow->setDispatchingTimeout(10ms);
5565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5566
5567 tapOnFocusedWindow();
5568 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005569 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5570 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5571 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572
5573 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005574 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5575 mFocusedWindow->getToken() == anrConnectionToken2);
5576 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5577 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005578
5579 ASSERT_TRUE(mDispatcher->waitForIdle());
5580 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005581
5582 mFocusedWindow->consumeMotionDown();
5583 mFocusedWindow->consumeMotionUp();
5584 mUnfocusedWindow->consumeMotionOutside();
5585
Prabir Pradhanedd96402022-02-15 01:46:16 -08005586 sp<IBinder> responsiveToken1, responsiveToken2;
5587 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5588 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005589
5590 // Both applications should be marked as responsive, in any order
5591 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5592 mFocusedWindow->getToken() == responsiveToken2);
5593 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5594 mUnfocusedWindow->getToken() == responsiveToken2);
5595 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005596}
5597
5598// If a window is already not responding, the second tap on the same window should be ignored.
5599// We should also log an error to account for the dropped event (not tested here).
5600// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5601TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5602 tapOnFocusedWindow();
5603 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5604 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5605 // Receive the events, but don't respond
5606 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5607 ASSERT_TRUE(downEventSequenceNum);
5608 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5609 ASSERT_TRUE(upEventSequenceNum);
5610 const std::chrono::duration timeout =
5611 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005612 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005613
5614 // Tap once again
5615 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005616 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5618 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005619 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005620 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5621 FOCUSED_WINDOW_LOCATION));
5622 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5623 // valid touch target
5624 mUnfocusedWindow->assertNoEvents();
5625
5626 // Consume the first tap
5627 mFocusedWindow->finishEvent(*downEventSequenceNum);
5628 mFocusedWindow->finishEvent(*upEventSequenceNum);
5629 ASSERT_TRUE(mDispatcher->waitForIdle());
5630 // The second tap did not go to the focused window
5631 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005632 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005633 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5634 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005635 mFakePolicy->assertNotifyAnrWasNotCalled();
5636}
5637
5638// If you tap outside of all windows, there will not be ANR
5639TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005640 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005641 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5642 LOCATION_OUTSIDE_ALL_WINDOWS));
5643 ASSERT_TRUE(mDispatcher->waitForIdle());
5644 mFakePolicy->assertNotifyAnrWasNotCalled();
5645}
5646
5647// Since the focused window is paused, tapping on it should not produce any events
5648TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5649 mFocusedWindow->setPaused(true);
5650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5651
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005652 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005653 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5654 FOCUSED_WINDOW_LOCATION));
5655
5656 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5657 ASSERT_TRUE(mDispatcher->waitForIdle());
5658 // Should not ANR because the window is paused, and touches shouldn't go to it
5659 mFakePolicy->assertNotifyAnrWasNotCalled();
5660
5661 mFocusedWindow->assertNoEvents();
5662 mUnfocusedWindow->assertNoEvents();
5663}
5664
5665/**
5666 * If a window is processing a motion event, and then a key event comes in, the key event should
5667 * not to to the focused window until the motion is processed.
5668 * If a different window becomes focused at this time, the key should go to that window instead.
5669 *
5670 * Warning!!!
5671 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5672 * and the injection timeout that we specify when injecting the key.
5673 * We must have the injection timeout (10ms) be smaller than
5674 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5675 *
5676 * If that value changes, this test should also change.
5677 */
5678TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5679 // Set a long ANR timeout to prevent it from triggering
5680 mFocusedWindow->setDispatchingTimeout(2s);
5681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5682
5683 tapOnUnfocusedWindow();
5684 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5685 ASSERT_TRUE(downSequenceNum);
5686 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5687 ASSERT_TRUE(upSequenceNum);
5688 // Don't finish the events yet, and send a key
5689 // Injection will succeed because we will eventually give up and send the key to the focused
5690 // window even if motions are still being processed.
5691
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005692 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005693 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005694 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005696 // Key will not be sent to the window, yet, because the window is still processing events
5697 // and the key remains pending, waiting for the touch events to be processed
5698 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5699 ASSERT_FALSE(keySequenceNum);
5700
5701 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005702 mFocusedWindow->setFocusable(false);
5703 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005705 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005706
5707 // Focus events should precede the key events
5708 mUnfocusedWindow->consumeFocusEvent(true);
5709 mFocusedWindow->consumeFocusEvent(false);
5710
5711 // Finish the tap events, which should unblock dispatcher
5712 mUnfocusedWindow->finishEvent(*downSequenceNum);
5713 mUnfocusedWindow->finishEvent(*upSequenceNum);
5714
5715 // Now that all queues are cleared and no backlog in the connections, the key event
5716 // can finally go to the newly focused "mUnfocusedWindow".
5717 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5718 mFocusedWindow->assertNoEvents();
5719 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005720 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005721}
5722
5723// When the touch stream is split across 2 windows, and one of them does not respond,
5724// then ANR should be raised and the touch should be canceled for the unresponsive window.
5725// The other window should not be affected by that.
5726TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5727 // Touch Window 1
5728 NotifyMotionArgs motionArgs =
5729 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5730 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5731 mDispatcher->notifyMotion(&motionArgs);
5732 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5733 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5734
5735 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005736 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5737 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005738 mDispatcher->notifyMotion(&motionArgs);
5739
5740 const std::chrono::duration timeout =
5741 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005742 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005743
5744 mUnfocusedWindow->consumeMotionDown();
5745 mFocusedWindow->consumeMotionDown();
5746 // Focused window may or may not receive ACTION_MOVE
5747 // But it should definitely receive ACTION_CANCEL due to the ANR
5748 InputEvent* event;
5749 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5750 ASSERT_TRUE(moveOrCancelSequenceNum);
5751 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5752 ASSERT_NE(nullptr, event);
5753 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5754 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5755 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5756 mFocusedWindow->consumeMotionCancel();
5757 } else {
5758 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5759 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005760 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005761 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5762 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005764 mUnfocusedWindow->assertNoEvents();
5765 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005766 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767}
5768
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005769/**
5770 * If we have no focused window, and a key comes in, we start the ANR timer.
5771 * The focused application should add a focused window before the timer runs out to prevent ANR.
5772 *
5773 * If the user touches another application during this time, the key should be dropped.
5774 * Next, if a new focused window comes in, without toggling the focused application,
5775 * then no ANR should occur.
5776 *
5777 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5778 * but in some cases the policy may not update the focused application.
5779 */
5780TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5781 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5782 std::make_shared<FakeApplicationHandle>();
5783 focusedApplication->setDispatchingTimeout(60ms);
5784 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5785 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5786 mFocusedWindow->setFocusable(false);
5787
5788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5789 mFocusedWindow->consumeFocusEvent(false);
5790
5791 // Send a key. The ANR timer should start because there is no focused window.
5792 // 'focusedApplication' will get blamed if this timer completes.
5793 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005794 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005795 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005796 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5797 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005799
5800 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5801 // then the injected touches won't cause the focused event to get dropped.
5802 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5803 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5804 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5805 // For this test, it means that the key would get delivered to the window once it becomes
5806 // focused.
5807 std::this_thread::sleep_for(10ms);
5808
5809 // Touch unfocused window. This should force the pending key to get dropped.
5810 NotifyMotionArgs motionArgs =
5811 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5812 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5813 mDispatcher->notifyMotion(&motionArgs);
5814
5815 // We do not consume the motion right away, because that would require dispatcher to first
5816 // process (== drop) the key event, and by that time, ANR will be raised.
5817 // Set the focused window first.
5818 mFocusedWindow->setFocusable(true);
5819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5820 setFocusedWindow(mFocusedWindow);
5821 mFocusedWindow->consumeFocusEvent(true);
5822 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5823 // to another application. This could be a bug / behaviour in the policy.
5824
5825 mUnfocusedWindow->consumeMotionDown();
5826
5827 ASSERT_TRUE(mDispatcher->waitForIdle());
5828 // Should not ANR because we actually have a focused window. It was just added too slowly.
5829 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5830}
5831
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005832// These tests ensure we cannot send touch events to a window that's positioned behind a window
5833// that has feature NO_INPUT_CHANNEL.
5834// Layout:
5835// Top (closest to user)
5836// mNoInputWindow (above all windows)
5837// mBottomWindow
5838// Bottom (furthest from user)
5839class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5840 virtual void SetUp() override {
5841 InputDispatcherTest::SetUp();
5842
5843 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005844 mNoInputWindow =
5845 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5846 "Window without input channel", ADISPLAY_ID_DEFAULT,
5847 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005848 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005849 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5850 // It's perfectly valid for this window to not have an associated input channel
5851
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005852 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5853 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005854 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5855
5856 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5857 }
5858
5859protected:
5860 std::shared_ptr<FakeApplicationHandle> mApplication;
5861 sp<FakeWindowHandle> mNoInputWindow;
5862 sp<FakeWindowHandle> mBottomWindow;
5863};
5864
5865TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5866 PointF touchedPoint = {10, 10};
5867
5868 NotifyMotionArgs motionArgs =
5869 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5870 ADISPLAY_ID_DEFAULT, {touchedPoint});
5871 mDispatcher->notifyMotion(&motionArgs);
5872
5873 mNoInputWindow->assertNoEvents();
5874 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5875 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5876 // and therefore should prevent mBottomWindow from receiving touches
5877 mBottomWindow->assertNoEvents();
5878}
5879
5880/**
5881 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5882 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5883 */
5884TEST_F(InputDispatcherMultiWindowOcclusionTests,
5885 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005886 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5887 "Window with input channel and NO_INPUT_CHANNEL",
5888 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005889
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005890 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005891 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5893
5894 PointF touchedPoint = {10, 10};
5895
5896 NotifyMotionArgs motionArgs =
5897 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5898 ADISPLAY_ID_DEFAULT, {touchedPoint});
5899 mDispatcher->notifyMotion(&motionArgs);
5900
5901 mNoInputWindow->assertNoEvents();
5902 mBottomWindow->assertNoEvents();
5903}
5904
Vishnu Nair958da932020-08-21 17:12:37 -07005905class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5906protected:
5907 std::shared_ptr<FakeApplicationHandle> mApp;
5908 sp<FakeWindowHandle> mWindow;
5909 sp<FakeWindowHandle> mMirror;
5910
5911 virtual void SetUp() override {
5912 InputDispatcherTest::SetUp();
5913 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005914 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5915 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5916 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005917 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5918 mWindow->setFocusable(true);
5919 mMirror->setFocusable(true);
5920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5921 }
5922};
5923
5924TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5925 // Request focus on a mirrored window
5926 setFocusedWindow(mMirror);
5927
5928 // window gets focused
5929 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5931 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005932 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5933}
5934
5935// A focused & mirrored window remains focused only if the window and its mirror are both
5936// focusable.
5937TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5938 setFocusedWindow(mMirror);
5939
5940 // window gets focused
5941 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5943 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005944 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5946 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005947 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5948
5949 mMirror->setFocusable(false);
5950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5951
5952 // window loses focus since one of the windows associated with the token in not focusable
5953 mWindow->consumeFocusEvent(false);
5954
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005955 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5956 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005957 mWindow->assertNoEvents();
5958}
5959
5960// A focused & mirrored window remains focused until the window and its mirror both become
5961// invisible.
5962TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5963 setFocusedWindow(mMirror);
5964
5965 // window gets focused
5966 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5968 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005969 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5971 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005972 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5973
5974 mMirror->setVisible(false);
5975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5976
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5978 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005979 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5981 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005982 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5983
5984 mWindow->setVisible(false);
5985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5986
5987 // window loses focus only after all windows associated with the token become invisible.
5988 mWindow->consumeFocusEvent(false);
5989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005990 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5991 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005992 mWindow->assertNoEvents();
5993}
5994
5995// A focused & mirrored window remains focused until both windows are removed.
5996TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5997 setFocusedWindow(mMirror);
5998
5999 // window gets focused
6000 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6002 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006003 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6005 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006006 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6007
6008 // single window is removed but the window token remains focused
6009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
6010
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6012 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006013 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6015 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006016 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6017
6018 // Both windows are removed
6019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
6020 mWindow->consumeFocusEvent(false);
6021
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006022 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6023 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006024 mWindow->assertNoEvents();
6025}
6026
6027// Focus request can be pending until one window becomes visible.
6028TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
6029 // Request focus on an invisible mirror.
6030 mWindow->setVisible(false);
6031 mMirror->setVisible(false);
6032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6033 setFocusedWindow(mMirror);
6034
6035 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07006037 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006038 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07006039
6040 mMirror->setVisible(true);
6041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6042
6043 // window gets focused
6044 mWindow->consumeFocusEvent(true);
6045 // window gets the pending key event
6046 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6047}
Prabir Pradhan99987712020-11-10 18:43:05 -08006048
6049class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
6050protected:
6051 std::shared_ptr<FakeApplicationHandle> mApp;
6052 sp<FakeWindowHandle> mWindow;
6053 sp<FakeWindowHandle> mSecondWindow;
6054
6055 void SetUp() override {
6056 InputDispatcherTest::SetUp();
6057 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006058 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006059 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006060 mSecondWindow =
6061 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006062 mSecondWindow->setFocusable(true);
6063
6064 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6066
6067 setFocusedWindow(mWindow);
6068 mWindow->consumeFocusEvent(true);
6069 }
6070
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006071 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
6072 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006073 mDispatcher->notifyPointerCaptureChanged(&args);
6074 }
6075
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006076 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
6077 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006078 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006079 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
6080 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006081 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006082 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08006083 }
6084};
6085
6086TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
6087 // Ensure that capture cannot be obtained for unfocused windows.
6088 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
6089 mFakePolicy->assertSetPointerCaptureNotCalled();
6090 mSecondWindow->assertNoEvents();
6091
6092 // Ensure that capture can be enabled from the focus window.
6093 requestAndVerifyPointerCapture(mWindow, true);
6094
6095 // Ensure that capture cannot be disabled from a window that does not have capture.
6096 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
6097 mFakePolicy->assertSetPointerCaptureNotCalled();
6098
6099 // Ensure that capture can be disabled from the window with capture.
6100 requestAndVerifyPointerCapture(mWindow, false);
6101}
6102
6103TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006104 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006105
6106 setFocusedWindow(mSecondWindow);
6107
6108 // Ensure that the capture disabled event was sent first.
6109 mWindow->consumeCaptureEvent(false);
6110 mWindow->consumeFocusEvent(false);
6111 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006112 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006113
6114 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006115 notifyPointerCaptureChanged({});
6116 notifyPointerCaptureChanged(request);
6117 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08006118 mWindow->assertNoEvents();
6119 mSecondWindow->assertNoEvents();
6120 mFakePolicy->assertSetPointerCaptureNotCalled();
6121}
6122
6123TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006124 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006125
6126 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006127 notifyPointerCaptureChanged({});
6128 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006129
6130 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006131 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006132 mWindow->consumeCaptureEvent(false);
6133 mWindow->assertNoEvents();
6134}
6135
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006136TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
6137 requestAndVerifyPointerCapture(mWindow, true);
6138
6139 // The first window loses focus.
6140 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006141 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006142 mWindow->consumeCaptureEvent(false);
6143
6144 // Request Pointer Capture from the second window before the notification from InputReader
6145 // arrives.
6146 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006147 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006148
6149 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006150 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006151
6152 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006153 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006154
6155 mSecondWindow->consumeFocusEvent(true);
6156 mSecondWindow->consumeCaptureEvent(true);
6157}
6158
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006159TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
6160 // App repeatedly enables and disables capture.
6161 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6162 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6163 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6164 mFakePolicy->assertSetPointerCaptureCalled(false);
6165 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6166 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6167
6168 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6169 // first request is now stale, this should do nothing.
6170 notifyPointerCaptureChanged(firstRequest);
6171 mWindow->assertNoEvents();
6172
6173 // InputReader notifies that the second request was enabled.
6174 notifyPointerCaptureChanged(secondRequest);
6175 mWindow->consumeCaptureEvent(true);
6176}
6177
Prabir Pradhan7092e262022-05-03 16:51:09 +00006178TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6179 requestAndVerifyPointerCapture(mWindow, true);
6180
6181 // App toggles pointer capture off and on.
6182 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6183 mFakePolicy->assertSetPointerCaptureCalled(false);
6184
6185 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6186 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6187
6188 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6189 // preceding "disable" request.
6190 notifyPointerCaptureChanged(enableRequest);
6191
6192 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6193 // any notifications.
6194 mWindow->assertNoEvents();
6195}
6196
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006197class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6198protected:
6199 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006200
6201 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6202 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6203
6204 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6205 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6206
6207 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6208 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6209 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6210 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6211 MAXIMUM_OBSCURING_OPACITY);
6212
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006213 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006214 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006215 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006216
6217 sp<FakeWindowHandle> mTouchWindow;
6218
6219 virtual void SetUp() override {
6220 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006221 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006222 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6223 }
6224
6225 virtual void TearDown() override {
6226 InputDispatcherTest::TearDown();
6227 mTouchWindow.clear();
6228 }
6229
chaviw3277faf2021-05-19 16:45:23 -05006230 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6231 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006232 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006233 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006234 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006235 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006236 return window;
6237 }
6238
6239 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6240 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6241 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006242 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006243 // Generate an arbitrary PID based on the UID
6244 window->setOwnerInfo(1777 + (uid % 10000), uid);
6245 return window;
6246 }
6247
6248 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6249 NotifyMotionArgs args =
6250 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6251 ADISPLAY_ID_DEFAULT, points);
6252 mDispatcher->notifyMotion(&args);
6253 }
6254};
6255
6256TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006257 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006258 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006260
6261 touch();
6262
6263 mTouchWindow->assertNoEvents();
6264}
6265
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006266TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006267 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6268 const sp<FakeWindowHandle>& w =
6269 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6271
6272 touch();
6273
6274 mTouchWindow->assertNoEvents();
6275}
6276
6277TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006278 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6279 const sp<FakeWindowHandle>& w =
6280 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6282
6283 touch();
6284
6285 w->assertNoEvents();
6286}
6287
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006288TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006289 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006291
6292 touch();
6293
6294 mTouchWindow->consumeAnyMotionDown();
6295}
6296
6297TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006298 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006299 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006300 w->setFrame(Rect(0, 0, 50, 50));
6301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006302
6303 touch({PointF{100, 100}});
6304
6305 mTouchWindow->consumeAnyMotionDown();
6306}
6307
6308TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006309 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006310 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6312
6313 touch();
6314
6315 mTouchWindow->consumeAnyMotionDown();
6316}
6317
6318TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6319 const sp<FakeWindowHandle>& w =
6320 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006322
6323 touch();
6324
6325 mTouchWindow->consumeAnyMotionDown();
6326}
6327
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006328TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6329 const sp<FakeWindowHandle>& w =
6330 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6332
6333 touch();
6334
6335 w->assertNoEvents();
6336}
6337
6338/**
6339 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6340 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6341 * window, the occluding window will still receive ACTION_OUTSIDE event.
6342 */
6343TEST_F(InputDispatcherUntrustedTouchesTest,
6344 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6345 const sp<FakeWindowHandle>& w =
6346 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006347 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6349
6350 touch();
6351
6352 w->consumeMotionOutside();
6353}
6354
6355TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6356 const sp<FakeWindowHandle>& w =
6357 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006358 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6360
6361 touch();
6362
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006363 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006364}
6365
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006366TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006367 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006368 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6369 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6371
6372 touch();
6373
6374 mTouchWindow->consumeAnyMotionDown();
6375}
6376
6377TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6378 const sp<FakeWindowHandle>& w =
6379 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6380 MAXIMUM_OBSCURING_OPACITY);
6381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006382
6383 touch();
6384
6385 mTouchWindow->consumeAnyMotionDown();
6386}
6387
6388TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006389 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006390 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6391 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6393
6394 touch();
6395
6396 mTouchWindow->assertNoEvents();
6397}
6398
6399TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6400 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6401 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006402 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6403 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006404 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006405 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6406 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6408
6409 touch();
6410
6411 mTouchWindow->assertNoEvents();
6412}
6413
6414TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6415 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6416 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006417 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6418 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006419 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006420 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6421 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6423
6424 touch();
6425
6426 mTouchWindow->consumeAnyMotionDown();
6427}
6428
6429TEST_F(InputDispatcherUntrustedTouchesTest,
6430 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6431 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006432 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6433 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006434 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006435 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6436 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6438
6439 touch();
6440
6441 mTouchWindow->consumeAnyMotionDown();
6442}
6443
6444TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6445 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006446 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6447 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006448 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006449 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6450 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006452
6453 touch();
6454
6455 mTouchWindow->assertNoEvents();
6456}
6457
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006458TEST_F(InputDispatcherUntrustedTouchesTest,
6459 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6460 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006461 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6462 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006463 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006464 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6465 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6467
6468 touch();
6469
6470 mTouchWindow->assertNoEvents();
6471}
6472
6473TEST_F(InputDispatcherUntrustedTouchesTest,
6474 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6475 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006476 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6477 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006478 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006479 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6480 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6482
6483 touch();
6484
6485 mTouchWindow->consumeAnyMotionDown();
6486}
6487
6488TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6489 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006490 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6491 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6493
6494 touch();
6495
6496 mTouchWindow->consumeAnyMotionDown();
6497}
6498
6499TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6500 const sp<FakeWindowHandle>& w =
6501 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6502 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6503
6504 touch();
6505
6506 mTouchWindow->consumeAnyMotionDown();
6507}
6508
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006509TEST_F(InputDispatcherUntrustedTouchesTest,
6510 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6511 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6512 const sp<FakeWindowHandle>& w =
6513 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6515
6516 touch();
6517
6518 mTouchWindow->assertNoEvents();
6519}
6520
6521TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6522 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6523 const sp<FakeWindowHandle>& w =
6524 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6526
6527 touch();
6528
6529 mTouchWindow->consumeAnyMotionDown();
6530}
6531
6532TEST_F(InputDispatcherUntrustedTouchesTest,
6533 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6534 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6535 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006536 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6537 OPACITY_ABOVE_THRESHOLD);
6538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6539
6540 touch();
6541
6542 mTouchWindow->consumeAnyMotionDown();
6543}
6544
6545TEST_F(InputDispatcherUntrustedTouchesTest,
6546 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6547 const sp<FakeWindowHandle>& w1 =
6548 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6549 OPACITY_BELOW_THRESHOLD);
6550 const sp<FakeWindowHandle>& w2 =
6551 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6552 OPACITY_BELOW_THRESHOLD);
6553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6554
6555 touch();
6556
6557 mTouchWindow->assertNoEvents();
6558}
6559
6560/**
6561 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6562 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6563 * (which alone would result in allowing touches) does not affect the blocking behavior.
6564 */
6565TEST_F(InputDispatcherUntrustedTouchesTest,
6566 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6567 const sp<FakeWindowHandle>& wB =
6568 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6569 OPACITY_BELOW_THRESHOLD);
6570 const sp<FakeWindowHandle>& wC =
6571 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6572 OPACITY_BELOW_THRESHOLD);
6573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6574
6575 touch();
6576
6577 mTouchWindow->assertNoEvents();
6578}
6579
6580/**
6581 * This test is testing that a window from a different UID but with same application token doesn't
6582 * block the touch. Apps can share the application token for close UI collaboration for example.
6583 */
6584TEST_F(InputDispatcherUntrustedTouchesTest,
6585 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6586 const sp<FakeWindowHandle>& w =
6587 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6588 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6590
6591 touch();
6592
6593 mTouchWindow->consumeAnyMotionDown();
6594}
6595
arthurhungb89ccb02020-12-30 16:19:01 +08006596class InputDispatcherDragTests : public InputDispatcherTest {
6597protected:
6598 std::shared_ptr<FakeApplicationHandle> mApp;
6599 sp<FakeWindowHandle> mWindow;
6600 sp<FakeWindowHandle> mSecondWindow;
6601 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006602 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006603 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6604 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006605
6606 void SetUp() override {
6607 InputDispatcherTest::SetUp();
6608 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006609 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006610 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006611
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006612 mSecondWindow =
6613 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006614 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006615
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006616 mSpyWindow =
6617 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006618 mSpyWindow->setSpy(true);
6619 mSpyWindow->setTrustedOverlay(true);
6620 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6621
arthurhungb89ccb02020-12-30 16:19:01 +08006622 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006624 }
6625
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006626 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6627 switch (fromSource) {
6628 case AINPUT_SOURCE_TOUCHSCREEN:
6629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6631 ADISPLAY_ID_DEFAULT, {50, 50}))
6632 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6633 break;
6634 case AINPUT_SOURCE_STYLUS:
6635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6636 injectMotionEvent(
6637 mDispatcher,
6638 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6639 AINPUT_SOURCE_STYLUS)
6640 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6641 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6642 .x(50)
6643 .y(50))
6644 .build()));
6645 break;
6646 case AINPUT_SOURCE_MOUSE:
6647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6648 injectMotionEvent(
6649 mDispatcher,
6650 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6651 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6652 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6653 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6654 .x(50)
6655 .y(50))
6656 .build()));
6657 break;
6658 default:
6659 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6660 }
arthurhungb89ccb02020-12-30 16:19:01 +08006661
6662 // Window should receive motion event.
6663 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006664 // Spy window should also receive motion event
6665 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006666 }
6667
6668 // Start performing drag, we will create a drag window and transfer touch to it.
6669 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6670 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006671 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006672 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006673 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006674 }
arthurhungb89ccb02020-12-30 16:19:01 +08006675
6676 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006677 mDragWindow =
6678 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006679 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006680 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006681 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006682
6683 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006684 bool transferred =
6685 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6686 true /* isDragDrop */);
6687 if (transferred) {
6688 mWindow->consumeMotionCancel();
6689 mDragWindow->consumeMotionDown();
6690 }
6691 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006692 }
6693};
6694
6695TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006696 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006697
6698 // Move on window.
6699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6700 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6701 ADISPLAY_ID_DEFAULT, {50, 50}))
6702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6703 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6704 mWindow->consumeDragEvent(false, 50, 50);
6705 mSecondWindow->assertNoEvents();
6706
6707 // Move to another window.
6708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6709 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6710 ADISPLAY_ID_DEFAULT, {150, 50}))
6711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6712 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6713 mWindow->consumeDragEvent(true, 150, 50);
6714 mSecondWindow->consumeDragEvent(false, 50, 50);
6715
6716 // Move back to original window.
6717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6718 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6719 ADISPLAY_ID_DEFAULT, {50, 50}))
6720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6721 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6722 mWindow->consumeDragEvent(false, 50, 50);
6723 mSecondWindow->consumeDragEvent(true, -50, 50);
6724
6725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6726 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6728 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6729 mWindow->assertNoEvents();
6730 mSecondWindow->assertNoEvents();
6731}
6732
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006733TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006734 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006735
6736 // No cancel event after drag start
6737 mSpyWindow->assertNoEvents();
6738
6739 const MotionEvent secondFingerDownEvent =
6740 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6741 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6742 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6743 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6744 .build();
6745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6746 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6747 InputEventInjectionSync::WAIT_FOR_RESULT))
6748 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6749
6750 // Receives cancel for first pointer after next pointer down
6751 mSpyWindow->consumeMotionCancel();
6752 mSpyWindow->consumeMotionDown();
6753
6754 mSpyWindow->assertNoEvents();
6755}
6756
arthurhungf452d0b2021-01-06 00:19:52 +08006757TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006758 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006759
6760 // Move on window.
6761 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6762 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6763 ADISPLAY_ID_DEFAULT, {50, 50}))
6764 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6765 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6766 mWindow->consumeDragEvent(false, 50, 50);
6767 mSecondWindow->assertNoEvents();
6768
6769 // Move to another window.
6770 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6771 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6772 ADISPLAY_ID_DEFAULT, {150, 50}))
6773 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6774 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6775 mWindow->consumeDragEvent(true, 150, 50);
6776 mSecondWindow->consumeDragEvent(false, 50, 50);
6777
6778 // drop to another window.
6779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6780 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6781 {150, 50}))
6782 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6783 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6784 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6785 mWindow->assertNoEvents();
6786 mSecondWindow->assertNoEvents();
6787}
6788
arthurhung6d4bed92021-03-17 11:59:33 +08006789TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006790 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006791
6792 // Move on window and keep button pressed.
6793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6794 injectMotionEvent(mDispatcher,
6795 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6796 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6797 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6798 .x(50)
6799 .y(50))
6800 .build()))
6801 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6802 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6803 mWindow->consumeDragEvent(false, 50, 50);
6804 mSecondWindow->assertNoEvents();
6805
6806 // Move to another window and release button, expect to drop item.
6807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6808 injectMotionEvent(mDispatcher,
6809 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6810 .buttonState(0)
6811 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6812 .x(150)
6813 .y(50))
6814 .build()))
6815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6816 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6817 mWindow->assertNoEvents();
6818 mSecondWindow->assertNoEvents();
6819 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6820
6821 // nothing to the window.
6822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6823 injectMotionEvent(mDispatcher,
6824 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6825 .buttonState(0)
6826 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6827 .x(150)
6828 .y(50))
6829 .build()))
6830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6831 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6832 mWindow->assertNoEvents();
6833 mSecondWindow->assertNoEvents();
6834}
6835
Arthur Hung54745652022-04-20 07:17:41 +00006836TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006837 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006838
6839 // Set second window invisible.
6840 mSecondWindow->setVisible(false);
6841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6842
6843 // Move on window.
6844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6845 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6846 ADISPLAY_ID_DEFAULT, {50, 50}))
6847 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6848 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6849 mWindow->consumeDragEvent(false, 50, 50);
6850 mSecondWindow->assertNoEvents();
6851
6852 // Move to another window.
6853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6854 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6855 ADISPLAY_ID_DEFAULT, {150, 50}))
6856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6857 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6858 mWindow->consumeDragEvent(true, 150, 50);
6859 mSecondWindow->assertNoEvents();
6860
6861 // drop to another window.
6862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6863 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6864 {150, 50}))
6865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6866 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6867 mFakePolicy->assertDropTargetEquals(nullptr);
6868 mWindow->assertNoEvents();
6869 mSecondWindow->assertNoEvents();
6870}
6871
Arthur Hung54745652022-04-20 07:17:41 +00006872TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006873 // Ensure window could track pointerIds if it didn't support split touch.
6874 mWindow->setPreventSplitting(true);
6875
Arthur Hung54745652022-04-20 07:17:41 +00006876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6877 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6878 {50, 50}))
6879 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6880 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6881
6882 const MotionEvent secondFingerDownEvent =
6883 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6884 .displayId(ADISPLAY_ID_DEFAULT)
6885 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6886 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6887 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6888 .build();
6889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6890 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6891 InputEventInjectionSync::WAIT_FOR_RESULT))
6892 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6893 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6894
6895 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006896 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006897}
6898
6899TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6900 // First down on second window.
6901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6903 {150, 50}))
6904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6905
6906 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6907
6908 // Second down on first window.
6909 const MotionEvent secondFingerDownEvent =
6910 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6911 .displayId(ADISPLAY_ID_DEFAULT)
6912 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6913 .pointer(
6914 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6915 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6916 .build();
6917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6918 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6919 InputEventInjectionSync::WAIT_FOR_RESULT))
6920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6921 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6922
6923 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006924 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006925
6926 // Move on window.
6927 const MotionEvent secondFingerMoveEvent =
6928 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6929 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6930 .pointer(
6931 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6932 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6933 .build();
6934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6935 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6936 InputEventInjectionSync::WAIT_FOR_RESULT));
6937 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6938 mWindow->consumeDragEvent(false, 50, 50);
6939 mSecondWindow->consumeMotionMove();
6940
6941 // Release the drag pointer should perform drop.
6942 const MotionEvent secondFingerUpEvent =
6943 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6944 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6945 .pointer(
6946 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6947 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6948 .build();
6949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6950 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6951 InputEventInjectionSync::WAIT_FOR_RESULT));
6952 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6953 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6954 mWindow->assertNoEvents();
6955 mSecondWindow->consumeMotionMove();
6956}
6957
Arthur Hung3915c1f2022-05-31 07:17:17 +00006958TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006959 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006960
6961 // Update window of second display.
6962 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006963 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006964 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6965
6966 // Let second display has a touch state.
6967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6968 injectMotionEvent(mDispatcher,
6969 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6970 AINPUT_SOURCE_TOUCHSCREEN)
6971 .displayId(SECOND_DISPLAY_ID)
6972 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6973 .x(100)
6974 .y(100))
6975 .build()));
6976 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6977 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6978 // Update window again.
6979 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6980
6981 // Move on window.
6982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6983 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6984 ADISPLAY_ID_DEFAULT, {50, 50}))
6985 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6986 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6987 mWindow->consumeDragEvent(false, 50, 50);
6988 mSecondWindow->assertNoEvents();
6989
6990 // Move to another window.
6991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6992 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6993 ADISPLAY_ID_DEFAULT, {150, 50}))
6994 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6995 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6996 mWindow->consumeDragEvent(true, 150, 50);
6997 mSecondWindow->consumeDragEvent(false, 50, 50);
6998
6999 // drop to another window.
7000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7001 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7002 {150, 50}))
7003 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7004 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7005 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7006 mWindow->assertNoEvents();
7007 mSecondWindow->assertNoEvents();
7008}
7009
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007010TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
7011 startDrag(true, AINPUT_SOURCE_MOUSE);
7012 // Move on window.
7013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7014 injectMotionEvent(mDispatcher,
7015 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7016 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7017 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7018 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7019 .x(50)
7020 .y(50))
7021 .build()))
7022 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7023 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7024 mWindow->consumeDragEvent(false, 50, 50);
7025 mSecondWindow->assertNoEvents();
7026
7027 // Move to another window.
7028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7029 injectMotionEvent(mDispatcher,
7030 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7031 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7032 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7033 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7034 .x(150)
7035 .y(50))
7036 .build()))
7037 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7038 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7039 mWindow->consumeDragEvent(true, 150, 50);
7040 mSecondWindow->consumeDragEvent(false, 50, 50);
7041
7042 // drop to another window.
7043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7044 injectMotionEvent(mDispatcher,
7045 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
7046 .buttonState(0)
7047 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7048 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7049 .x(150)
7050 .y(50))
7051 .build()))
7052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7053 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7054 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7055 mWindow->assertNoEvents();
7056 mSecondWindow->assertNoEvents();
7057}
7058
Vishnu Nair062a8672021-09-03 16:07:44 -07007059class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
7060
7061TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
7062 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007063 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7064 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007065 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007066 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7067 window->setFocusable(true);
7068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7069 setFocusedWindow(window);
7070 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7071
7072 // With the flag set, window should not get any input
7073 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7074 mDispatcher->notifyKey(&keyArgs);
7075 window->assertNoEvents();
7076
7077 NotifyMotionArgs motionArgs =
7078 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7079 ADISPLAY_ID_DEFAULT);
7080 mDispatcher->notifyMotion(&motionArgs);
7081 window->assertNoEvents();
7082
7083 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007084 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007085 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7086
7087 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7088 mDispatcher->notifyKey(&keyArgs);
7089 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7090
7091 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7092 ADISPLAY_ID_DEFAULT);
7093 mDispatcher->notifyMotion(&motionArgs);
7094 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7095 window->assertNoEvents();
7096}
7097
7098TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
7099 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7100 std::make_shared<FakeApplicationHandle>();
7101 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007102 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7103 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007104 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7105 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007106 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007107 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007108 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7109 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007110 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007111 window->setOwnerInfo(222, 222);
7112 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7113 window->setFocusable(true);
7114 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7115 setFocusedWindow(window);
7116 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7117
7118 // With the flag set, window should not get any input
7119 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7120 mDispatcher->notifyKey(&keyArgs);
7121 window->assertNoEvents();
7122
7123 NotifyMotionArgs motionArgs =
7124 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7125 ADISPLAY_ID_DEFAULT);
7126 mDispatcher->notifyMotion(&motionArgs);
7127 window->assertNoEvents();
7128
7129 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007130 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7132
7133 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7134 mDispatcher->notifyKey(&keyArgs);
7135 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7136
7137 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7138 ADISPLAY_ID_DEFAULT);
7139 mDispatcher->notifyMotion(&motionArgs);
7140 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
7141 window->assertNoEvents();
7142}
7143
7144TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
7145 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7146 std::make_shared<FakeApplicationHandle>();
7147 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007148 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7149 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007150 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7151 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007152 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007153 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007154 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7155 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007156 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007157 window->setOwnerInfo(222, 222);
7158 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7159 window->setFocusable(true);
7160 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7161 setFocusedWindow(window);
7162 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7163
7164 // With the flag set, window should not get any input
7165 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7166 mDispatcher->notifyKey(&keyArgs);
7167 window->assertNoEvents();
7168
7169 NotifyMotionArgs motionArgs =
7170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7171 ADISPLAY_ID_DEFAULT);
7172 mDispatcher->notifyMotion(&motionArgs);
7173 window->assertNoEvents();
7174
7175 // When the window is no longer obscured because it went on top, it should get input
7176 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7177
7178 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7179 mDispatcher->notifyKey(&keyArgs);
7180 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7181
7182 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7183 ADISPLAY_ID_DEFAULT);
7184 mDispatcher->notifyMotion(&motionArgs);
7185 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7186 window->assertNoEvents();
7187}
7188
Antonio Kantekf16f2832021-09-28 04:39:20 +00007189class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7190protected:
7191 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007192 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007193 sp<FakeWindowHandle> mWindow;
7194 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007195 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007196
7197 void SetUp() override {
7198 InputDispatcherTest::SetUp();
7199
7200 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007201 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007202 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007203 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007204 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007205 mSecondWindow =
7206 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007207 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007208 mThirdWindow =
7209 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7210 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7211 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007212
7213 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7215 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7216 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007217 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007218
Antonio Kantek15beb512022-06-13 22:35:41 +00007219 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007220 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00007221 WINDOW_UID, true /* hasPermission */,
7222 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007223 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7224 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007225 mThirdWindow->assertNoEvents();
7226 }
7227
7228 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7229 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
7230 SECONDARY_WINDOW_UID, true /* hasPermission */,
7231 SECOND_DISPLAY_ID)) {
7232 mWindow->assertNoEvents();
7233 mSecondWindow->assertNoEvents();
7234 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007235 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007236 }
7237
Antonio Kantek15beb512022-06-13 22:35:41 +00007238 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7239 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007240 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7241 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007242 mWindow->consumeTouchModeEvent(inTouchMode);
7243 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007244 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007245 }
7246};
7247
Antonio Kantek26defcf2022-02-08 01:12:27 +00007248TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007249 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007250 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7251 windowInfo.ownerPid, windowInfo.ownerUid,
7252 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007253}
7254
Antonio Kantek26defcf2022-02-08 01:12:27 +00007255TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7256 const WindowInfo& windowInfo = *mWindow->getInfo();
7257 int32_t ownerPid = windowInfo.ownerPid;
7258 int32_t ownerUid = windowInfo.ownerUid;
7259 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7260 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007261 ownerUid, false /*hasPermission*/,
7262 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007263 mWindow->assertNoEvents();
7264 mSecondWindow->assertNoEvents();
7265}
7266
7267TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7268 const WindowInfo& windowInfo = *mWindow->getInfo();
7269 int32_t ownerPid = windowInfo.ownerPid;
7270 int32_t ownerUid = windowInfo.ownerUid;
7271 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007272 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
7273 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007274}
7275
Antonio Kantekf16f2832021-09-28 04:39:20 +00007276TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007277 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007278 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7279 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007280 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007281 mWindow->assertNoEvents();
7282 mSecondWindow->assertNoEvents();
7283}
7284
Antonio Kantek15beb512022-06-13 22:35:41 +00007285TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7286 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7287 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7288 windowInfo.ownerPid, windowInfo.ownerUid,
7289 true /*hasPermission*/, SECOND_DISPLAY_ID));
7290 mWindow->assertNoEvents();
7291 mSecondWindow->assertNoEvents();
7292 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7293}
7294
Antonio Kantek48710e42022-03-24 14:19:30 -07007295TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7296 // Interact with the window first.
7297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7298 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7299 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7300
7301 // Then remove focus.
7302 mWindow->setFocusable(false);
7303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7304
7305 // Assert that caller can switch touch mode by owning one of the last interacted window.
7306 const WindowInfo& windowInfo = *mWindow->getInfo();
7307 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7308 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007309 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007310}
7311
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007312class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7313public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007314 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007315 std::shared_ptr<FakeApplicationHandle> application =
7316 std::make_shared<FakeApplicationHandle>();
7317 std::string name = "Fake Spy ";
7318 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007319 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7320 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007321 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007322 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007323 return spy;
7324 }
7325
7326 sp<FakeWindowHandle> createForeground() {
7327 std::shared_ptr<FakeApplicationHandle> application =
7328 std::make_shared<FakeApplicationHandle>();
7329 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007330 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7331 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007332 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007333 return window;
7334 }
7335
7336private:
7337 int mSpyCount{0};
7338};
7339
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007340using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007341/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007342 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7343 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007344TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7345 ScopedSilentDeath _silentDeath;
7346
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007347 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007348 spy->setTrustedOverlay(false);
7349 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7350 ".* not a trusted overlay");
7351}
7352
7353/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007354 * Input injection into a display with a spy window but no foreground windows should succeed.
7355 */
7356TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007357 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7359
7360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7361 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7362 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7363 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7364}
7365
7366/**
7367 * Verify the order in which different input windows receive events. The touched foreground window
7368 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7369 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7370 * receive events before ones belows it.
7371 *
7372 * Here, we set up a scenario with four windows in the following Z order from the top:
7373 * spy1, spy2, window, spy3.
7374 * We then inject an event and verify that the foreground "window" receives it first, followed by
7375 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7376 * window.
7377 */
7378TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7379 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007380 auto spy1 = createSpy();
7381 auto spy2 = createSpy();
7382 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7384 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7385 const size_t numChannels = channels.size();
7386
Michael Wright8e9a8562022-02-09 13:44:29 +00007387 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007388 if (!epollFd.ok()) {
7389 FAIL() << "Failed to create epoll fd";
7390 }
7391
7392 for (size_t i = 0; i < numChannels; i++) {
7393 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7394 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7395 FAIL() << "Failed to add fd to epoll";
7396 }
7397 }
7398
7399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7400 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7401 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7402
7403 std::vector<size_t> eventOrder;
7404 std::vector<struct epoll_event> events(numChannels);
7405 for (;;) {
7406 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7407 (100ms).count());
7408 if (nFds < 0) {
7409 FAIL() << "Failed to call epoll_wait";
7410 }
7411 if (nFds == 0) {
7412 break; // epoll_wait timed out
7413 }
7414 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007415 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007416 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007417 channels[i]->consumeMotionDown();
7418 }
7419 }
7420
7421 // Verify the order in which the events were received.
7422 EXPECT_EQ(3u, eventOrder.size());
7423 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7424 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7425 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7426}
7427
7428/**
7429 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7430 */
7431TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7432 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007433 auto spy = createSpy();
7434 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7436
7437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7438 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7439 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7440 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7441 spy->assertNoEvents();
7442}
7443
7444/**
7445 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7446 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7447 * to the window.
7448 */
7449TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7450 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007451 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007452 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7454
7455 // Inject an event outside the spy window's touchable region.
7456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7459 window->consumeMotionDown();
7460 spy->assertNoEvents();
7461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7462 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7464 window->consumeMotionUp();
7465 spy->assertNoEvents();
7466
7467 // Inject an event inside the spy window's touchable region.
7468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7470 {5, 10}))
7471 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7472 window->consumeMotionDown();
7473 spy->consumeMotionDown();
7474}
7475
7476/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007477 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007478 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007479 */
7480TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7481 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007482 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007483 auto spy = createSpy();
7484 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007485 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007486 spy->setFrame(Rect{0, 0, 20, 20});
7487 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7488
7489 // Inject an event outside the spy window's frame and touchable region.
7490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007491 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7492 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007493 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7494 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007495 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007496}
7497
7498/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007499 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7500 * pointers that are down within its bounds.
7501 */
7502TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7503 auto windowLeft = createForeground();
7504 windowLeft->setFrame({0, 0, 100, 200});
7505 auto windowRight = createForeground();
7506 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007507 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007508 spy->setFrame({0, 0, 200, 200});
7509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7510
7511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7513 {50, 50}))
7514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7515 windowLeft->consumeMotionDown();
7516 spy->consumeMotionDown();
7517
7518 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007519 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007520 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7521 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7522 .pointer(
7523 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7524 .build();
7525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7526 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7527 InputEventInjectionSync::WAIT_FOR_RESULT))
7528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7529 windowRight->consumeMotionDown();
7530 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7531}
7532
7533/**
7534 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7535 * the spy should receive the second pointer with ACTION_DOWN.
7536 */
7537TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7538 auto window = createForeground();
7539 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007540 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007541 spyRight->setFrame({100, 0, 200, 200});
7542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7543
7544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7545 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7546 {50, 50}))
7547 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7548 window->consumeMotionDown();
7549 spyRight->assertNoEvents();
7550
7551 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007552 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007553 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7554 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7555 .pointer(
7556 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7557 .build();
7558 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7559 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7560 InputEventInjectionSync::WAIT_FOR_RESULT))
7561 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7562 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7563 spyRight->consumeMotionDown();
7564}
7565
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007566/**
7567 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7568 * windows should be allowed to control split touch.
7569 */
7570TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007571 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007572 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007573 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007574 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007575
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007576 auto window = createForeground();
7577 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007578
7579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7580
7581 // First finger down, no window touched.
7582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7584 {100, 200}))
7585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7586 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7587 window->assertNoEvents();
7588
7589 // Second finger down on window, the window should receive touch down.
7590 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007591 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007592 .displayId(ADISPLAY_ID_DEFAULT)
7593 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7594 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7595 .x(100)
7596 .y(200))
7597 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7598 .build();
7599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7600 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7601 InputEventInjectionSync::WAIT_FOR_RESULT))
7602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7603
7604 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7605 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7606}
7607
7608/**
7609 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7610 * do not receive key events.
7611 */
7612TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007613 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007614 spy->setFocusable(false);
7615
7616 auto window = createForeground();
7617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7618 setFocusedWindow(window);
7619 window->consumeFocusEvent(true);
7620
7621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7622 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7623 window->consumeKeyDown(ADISPLAY_ID_NONE);
7624
7625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7627 window->consumeKeyUp(ADISPLAY_ID_NONE);
7628
7629 spy->assertNoEvents();
7630}
7631
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007632using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7633
7634/**
7635 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7636 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7637 */
7638TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7639 auto window = createForeground();
7640 auto spy1 = createSpy();
7641 auto spy2 = createSpy();
7642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7643
7644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7645 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7647 window->consumeMotionDown();
7648 spy1->consumeMotionDown();
7649 spy2->consumeMotionDown();
7650
7651 // Pilfer pointers from the second spy window.
7652 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7653 spy2->assertNoEvents();
7654 spy1->consumeMotionCancel();
7655 window->consumeMotionCancel();
7656
7657 // The rest of the gesture should only be sent to the second spy window.
7658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7659 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7660 ADISPLAY_ID_DEFAULT))
7661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7662 spy2->consumeMotionMove();
7663 spy1->assertNoEvents();
7664 window->assertNoEvents();
7665}
7666
7667/**
7668 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7669 * in the middle of the gesture.
7670 */
7671TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7672 auto window = createForeground();
7673 auto spy = createSpy();
7674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7675
7676 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7677 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7678 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7679 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7680 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7681
7682 window->releaseChannel();
7683
7684 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7685
7686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7687 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7688 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7689 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7690}
7691
7692/**
7693 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7694 * the spy, but not to any other windows.
7695 */
7696TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7697 auto spy = createSpy();
7698 auto window = createForeground();
7699
7700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7701
7702 // First finger down on the window and the spy.
7703 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7704 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7705 {100, 200}))
7706 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7707 spy->consumeMotionDown();
7708 window->consumeMotionDown();
7709
7710 // Spy window pilfers the pointers.
7711 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7712 window->consumeMotionCancel();
7713
7714 // Second finger down on the window and spy, but the window should not receive the pointer down.
7715 const MotionEvent secondFingerDownEvent =
7716 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7717 .displayId(ADISPLAY_ID_DEFAULT)
7718 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7719 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7720 .x(100)
7721 .y(200))
7722 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7723 .build();
7724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7725 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7726 InputEventInjectionSync::WAIT_FOR_RESULT))
7727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7728
7729 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7730
7731 // Third finger goes down outside all windows, so injection should fail.
7732 const MotionEvent thirdFingerDownEvent =
7733 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7734 .displayId(ADISPLAY_ID_DEFAULT)
7735 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7736 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7737 .x(100)
7738 .y(200))
7739 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7740 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7741 .build();
7742 ASSERT_EQ(InputEventInjectionResult::FAILED,
7743 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7744 InputEventInjectionSync::WAIT_FOR_RESULT))
7745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7746
7747 spy->assertNoEvents();
7748 window->assertNoEvents();
7749}
7750
7751/**
7752 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7753 */
7754TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7755 auto spy = createSpy();
7756 spy->setFrame(Rect(0, 0, 100, 100));
7757 auto window = createForeground();
7758 window->setFrame(Rect(0, 0, 200, 200));
7759
7760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7761
7762 // First finger down on the window only
7763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7764 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7765 {150, 150}))
7766 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7767 window->consumeMotionDown();
7768
7769 // Second finger down on the spy and window
7770 const MotionEvent secondFingerDownEvent =
7771 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7772 .displayId(ADISPLAY_ID_DEFAULT)
7773 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7774 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7775 .x(150)
7776 .y(150))
7777 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7778 .build();
7779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7780 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7781 InputEventInjectionSync::WAIT_FOR_RESULT))
7782 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7783 spy->consumeMotionDown();
7784 window->consumeMotionPointerDown(1);
7785
7786 // Third finger down on the spy and window
7787 const MotionEvent thirdFingerDownEvent =
7788 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7789 .displayId(ADISPLAY_ID_DEFAULT)
7790 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7791 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7792 .x(150)
7793 .y(150))
7794 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7795 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7796 .build();
7797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7798 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7799 InputEventInjectionSync::WAIT_FOR_RESULT))
7800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7801 spy->consumeMotionPointerDown(1);
7802 window->consumeMotionPointerDown(2);
7803
7804 // Spy window pilfers the pointers.
7805 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7806 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7807 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7808
7809 spy->assertNoEvents();
7810 window->assertNoEvents();
7811}
7812
7813/**
7814 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7815 * other windows should be canceled. If this results in the cancellation of all pointers for some
7816 * window, then that window should receive ACTION_CANCEL.
7817 */
7818TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7819 auto spy = createSpy();
7820 spy->setFrame(Rect(0, 0, 100, 100));
7821 auto window = createForeground();
7822 window->setFrame(Rect(0, 0, 200, 200));
7823
7824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7825
7826 // First finger down on both spy and window
7827 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7828 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7829 {10, 10}))
7830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7831 window->consumeMotionDown();
7832 spy->consumeMotionDown();
7833
7834 // Second finger down on the spy and window
7835 const MotionEvent secondFingerDownEvent =
7836 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7837 .displayId(ADISPLAY_ID_DEFAULT)
7838 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7839 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7840 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7841 .build();
7842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7843 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7844 InputEventInjectionSync::WAIT_FOR_RESULT))
7845 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7846 spy->consumeMotionPointerDown(1);
7847 window->consumeMotionPointerDown(1);
7848
7849 // Spy window pilfers the pointers.
7850 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7851 window->consumeMotionCancel();
7852
7853 spy->assertNoEvents();
7854 window->assertNoEvents();
7855}
7856
7857/**
7858 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7859 * be sent to other windows
7860 */
7861TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7862 auto spy = createSpy();
7863 spy->setFrame(Rect(0, 0, 100, 100));
7864 auto window = createForeground();
7865 window->setFrame(Rect(0, 0, 200, 200));
7866
7867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7868
7869 // First finger down on both window and spy
7870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7871 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7872 {10, 10}))
7873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7874 window->consumeMotionDown();
7875 spy->consumeMotionDown();
7876
7877 // Spy window pilfers the pointers.
7878 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7879 window->consumeMotionCancel();
7880
7881 // Second finger down on the window only
7882 const MotionEvent secondFingerDownEvent =
7883 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7884 .displayId(ADISPLAY_ID_DEFAULT)
7885 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7886 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7887 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7888 .x(150)
7889 .y(150))
7890 .build();
7891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7892 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7893 InputEventInjectionSync::WAIT_FOR_RESULT))
7894 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7895 window->consumeMotionDown();
7896 window->assertNoEvents();
7897
7898 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7899 spy->consumeMotionMove();
7900 spy->assertNoEvents();
7901}
7902
Prabir Pradhand65552b2021-10-07 11:23:50 -07007903class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7904public:
7905 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7906 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7907 std::make_shared<FakeApplicationHandle>();
7908 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007909 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7910 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007911 overlay->setFocusable(false);
7912 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007913 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007914 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007915 overlay->setTrustedOverlay(true);
7916
7917 std::shared_ptr<FakeApplicationHandle> application =
7918 std::make_shared<FakeApplicationHandle>();
7919 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007920 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7921 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007922 window->setFocusable(true);
7923 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007924
7925 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7927 setFocusedWindow(window);
7928 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7929 return {std::move(overlay), std::move(window)};
7930 }
7931
7932 void sendFingerEvent(int32_t action) {
7933 NotifyMotionArgs motionArgs =
7934 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7935 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7936 mDispatcher->notifyMotion(&motionArgs);
7937 }
7938
7939 void sendStylusEvent(int32_t action) {
7940 NotifyMotionArgs motionArgs =
7941 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7942 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7943 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7944 mDispatcher->notifyMotion(&motionArgs);
7945 }
7946};
7947
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007948using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7949
7950TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7951 ScopedSilentDeath _silentDeath;
7952
Prabir Pradhand65552b2021-10-07 11:23:50 -07007953 auto [overlay, window] = setupStylusOverlayScenario();
7954 overlay->setTrustedOverlay(false);
7955 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7956 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7957 ".* not a trusted overlay");
7958}
7959
7960TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7961 auto [overlay, window] = setupStylusOverlayScenario();
7962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7963
7964 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7965 overlay->consumeMotionDown();
7966 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7967 overlay->consumeMotionUp();
7968
7969 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7970 window->consumeMotionDown();
7971 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7972 window->consumeMotionUp();
7973
7974 overlay->assertNoEvents();
7975 window->assertNoEvents();
7976}
7977
7978TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7979 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007980 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7982
7983 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7984 overlay->consumeMotionDown();
7985 window->consumeMotionDown();
7986 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7987 overlay->consumeMotionUp();
7988 window->consumeMotionUp();
7989
7990 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7991 window->consumeMotionDown();
7992 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7993 window->consumeMotionUp();
7994
7995 overlay->assertNoEvents();
7996 window->assertNoEvents();
7997}
7998
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007999/**
8000 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
8001 * The scenario is as follows:
8002 * - The stylus interceptor overlay is configured as a spy window.
8003 * - The stylus interceptor spy receives the start of a new stylus gesture.
8004 * - It pilfers pointers and then configures itself to no longer be a spy.
8005 * - The stylus interceptor continues to receive the rest of the gesture.
8006 */
8007TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
8008 auto [overlay, window] = setupStylusOverlayScenario();
8009 overlay->setSpy(true);
8010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8011
8012 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8013 overlay->consumeMotionDown();
8014 window->consumeMotionDown();
8015
8016 // The interceptor pilfers the pointers.
8017 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
8018 window->consumeMotionCancel();
8019
8020 // The interceptor configures itself so that it is no longer a spy.
8021 overlay->setSpy(false);
8022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8023
8024 // It continues to receive the rest of the stylus gesture.
8025 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
8026 overlay->consumeMotionMove();
8027 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8028 overlay->consumeMotionUp();
8029
8030 window->assertNoEvents();
8031}
8032
Prabir Pradhan5735a322022-04-11 17:23:34 +00008033struct User {
8034 int32_t mPid;
8035 int32_t mUid;
8036 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
8037 std::unique_ptr<InputDispatcher>& mDispatcher;
8038
8039 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
8040 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
8041
8042 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
8043 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
8044 ADISPLAY_ID_DEFAULT, {100, 200},
8045 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
8046 AMOTION_EVENT_INVALID_CURSOR_POSITION},
8047 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
8048 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
8049 }
8050
8051 InputEventInjectionResult injectTargetedKey(int32_t action) const {
8052 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
8053 InputEventInjectionSync::WAIT_FOR_RESULT,
8054 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
8055 mPolicyFlags);
8056 }
8057
8058 sp<FakeWindowHandle> createWindow() const {
8059 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8060 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008061 sp<FakeWindowHandle> window =
8062 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
8063 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00008064 window->setOwnerInfo(mPid, mUid);
8065 return window;
8066 }
8067};
8068
8069using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
8070
8071TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
8072 auto owner = User(mDispatcher, 10, 11);
8073 auto window = owner.createWindow();
8074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8075
8076 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8077 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8078 window->consumeMotionDown();
8079
8080 setFocusedWindow(window);
8081 window->consumeFocusEvent(true);
8082
8083 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8084 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8085 window->consumeKeyDown(ADISPLAY_ID_NONE);
8086}
8087
8088TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
8089 auto owner = User(mDispatcher, 10, 11);
8090 auto window = owner.createWindow();
8091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8092
8093 auto rando = User(mDispatcher, 20, 21);
8094 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8095 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8096
8097 setFocusedWindow(window);
8098 window->consumeFocusEvent(true);
8099
8100 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8101 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8102 window->assertNoEvents();
8103}
8104
8105TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
8106 auto owner = User(mDispatcher, 10, 11);
8107 auto window = owner.createWindow();
8108 auto spy = owner.createWindow();
8109 spy->setSpy(true);
8110 spy->setTrustedOverlay(true);
8111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8112
8113 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8114 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8115 spy->consumeMotionDown();
8116 window->consumeMotionDown();
8117}
8118
8119TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
8120 auto owner = User(mDispatcher, 10, 11);
8121 auto window = owner.createWindow();
8122
8123 auto rando = User(mDispatcher, 20, 21);
8124 auto randosSpy = rando.createWindow();
8125 randosSpy->setSpy(true);
8126 randosSpy->setTrustedOverlay(true);
8127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8128
8129 // The event is targeted at owner's window, so injection should succeed, but the spy should
8130 // not receive the event.
8131 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8132 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8133 randosSpy->assertNoEvents();
8134 window->consumeMotionDown();
8135}
8136
8137TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
8138 auto owner = User(mDispatcher, 10, 11);
8139 auto window = owner.createWindow();
8140
8141 auto rando = User(mDispatcher, 20, 21);
8142 auto randosSpy = rando.createWindow();
8143 randosSpy->setSpy(true);
8144 randosSpy->setTrustedOverlay(true);
8145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8146
8147 // A user that has injection permission can inject into any window.
8148 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8149 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8150 ADISPLAY_ID_DEFAULT));
8151 randosSpy->consumeMotionDown();
8152 window->consumeMotionDown();
8153
8154 setFocusedWindow(randosSpy);
8155 randosSpy->consumeFocusEvent(true);
8156
8157 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
8158 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
8159 window->assertNoEvents();
8160}
8161
8162TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
8163 auto owner = User(mDispatcher, 10, 11);
8164 auto window = owner.createWindow();
8165
8166 auto rando = User(mDispatcher, 20, 21);
8167 auto randosWindow = rando.createWindow();
8168 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8169 randosWindow->setWatchOutsideTouch(true);
8170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8171
8172 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8173 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8174 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8175 window->consumeMotionDown();
8176 randosWindow->consumeMotionOutside();
8177}
8178
Garfield Tane84e6f92019-08-29 17:28:41 -07008179} // namespace android::inputdispatcher