blob: 3abe43a69fd773bb3cbc414a9955a0b0acc43b9d [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));
Garfield Tandf26e862020-07-01 20:18:19 -07002171
2172 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002174 injectMotionEvent(mDispatcher,
2175 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2176 AINPUT_SOURCE_MOUSE)
2177 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2178 .x(300)
2179 .y(400))
2180 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002181 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2182 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002183
2184 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002186 injectMotionEvent(mDispatcher,
2187 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2188 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2189 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2190 .x(300)
2191 .y(400))
2192 .build()));
2193 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2194
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002196 injectMotionEvent(mDispatcher,
2197 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2198 AINPUT_SOURCE_MOUSE)
2199 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2200 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2201 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2202 .x(300)
2203 .y(400))
2204 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002205 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002206
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002207 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002208 injectMotionEvent(mDispatcher,
2209 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2210 AINPUT_SOURCE_MOUSE)
2211 .buttonState(0)
2212 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2213 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2214 .x(300)
2215 .y(400))
2216 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002217 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002218
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002220 injectMotionEvent(mDispatcher,
2221 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2222 .buttonState(0)
2223 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2224 .x(300)
2225 .y(400))
2226 .build()));
2227 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2228
2229 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002231 injectMotionEvent(mDispatcher,
2232 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2233 AINPUT_SOURCE_MOUSE)
2234 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2235 .x(900)
2236 .y(400))
2237 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002238 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2239 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002240
2241 // No more events
2242 windowLeft->assertNoEvents();
2243 windowRight->assertNoEvents();
2244}
2245
2246TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
2247 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2248
2249 sp<FakeWindowHandle> spyWindow =
2250 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2251 spyWindow->setFrame(Rect(0, 0, 600, 800));
2252 spyWindow->setTrustedOverlay(true);
2253 spyWindow->setSpy(true);
2254 sp<FakeWindowHandle> window =
2255 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2256 window->setFrame(Rect(0, 0, 600, 800));
2257
2258 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2260
2261 // Send mouse cursor to the window
2262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2263 injectMotionEvent(mDispatcher,
2264 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2265 AINPUT_SOURCE_MOUSE)
2266 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2267 .x(100)
2268 .y(100))
2269 .build()));
2270
2271 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2272 WithSource(AINPUT_SOURCE_MOUSE)));
2273 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2274 WithSource(AINPUT_SOURCE_MOUSE)));
2275
2276 window->assertNoEvents();
2277 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07002278}
2279
2280// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2281// directly in this test.
2282TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002284 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002285 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002286 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002287
2288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2289
2290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002293 injectMotionEvent(mDispatcher,
2294 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2295 AINPUT_SOURCE_MOUSE)
2296 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2297 .x(300)
2298 .y(400))
2299 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002300 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002301 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002303 injectMotionEvent(mDispatcher,
2304 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2305 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2306 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2307 .x(300)
2308 .y(400))
2309 .build()));
2310 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2311
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002313 injectMotionEvent(mDispatcher,
2314 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2315 AINPUT_SOURCE_MOUSE)
2316 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2317 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2318 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2319 .x(300)
2320 .y(400))
2321 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002322 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002323
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002325 injectMotionEvent(mDispatcher,
2326 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2327 AINPUT_SOURCE_MOUSE)
2328 .buttonState(0)
2329 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2330 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2331 .x(300)
2332 .y(400))
2333 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002334 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002335
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002337 injectMotionEvent(mDispatcher,
2338 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2339 .buttonState(0)
2340 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2341 .x(300)
2342 .y(400))
2343 .build()));
2344 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002347 injectMotionEvent(mDispatcher,
2348 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2349 AINPUT_SOURCE_MOUSE)
2350 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2351 .x(300)
2352 .y(400))
2353 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002354 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
Garfield Tandf26e862020-07-01 20:18:19 -07002355}
2356
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002357/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002358 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
2359 * is generated.
2360 */
2361TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
2362 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2363 sp<FakeWindowHandle> window =
2364 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2365 window->setFrame(Rect(0, 0, 1200, 800));
2366
2367 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2368
2369 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2370
2371 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2372 injectMotionEvent(mDispatcher,
2373 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2374 AINPUT_SOURCE_MOUSE)
2375 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2376 .x(300)
2377 .y(400))
2378 .build()));
2379 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2380
2381 // Remove the window, but keep the channel.
2382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2383 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2384}
2385
2386/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002387 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002388 * The tap causes a HOVER_EXIT event to be generated because the current event
2389 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002390 */
2391TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2392 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2393 sp<FakeWindowHandle> window =
2394 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2395 window->setFrame(Rect(0, 0, 100, 100));
2396
2397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2398
2399 // Inject a hover_move from mouse.
2400 NotifyMotionArgs motionArgs =
2401 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2402 ADISPLAY_ID_DEFAULT, {{50, 50}});
2403 motionArgs.xCursorPosition = 50;
2404 motionArgs.yCursorPosition = 50;
2405 mDispatcher->notifyMotion(&motionArgs);
2406 ASSERT_NO_FATAL_FAILURE(
2407 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2408 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002409
2410 // Tap on the window
2411 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2412 ADISPLAY_ID_DEFAULT, {{10, 10}});
2413 mDispatcher->notifyMotion(&motionArgs);
2414 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002415 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2416 WithSource(AINPUT_SOURCE_MOUSE))));
2417
2418 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002419 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2420 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2421
2422 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2423 ADISPLAY_ID_DEFAULT, {{10, 10}});
2424 mDispatcher->notifyMotion(&motionArgs);
2425 ASSERT_NO_FATAL_FAILURE(
2426 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2427 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2428}
2429
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002430TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2431 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2432 sp<FakeWindowHandle> windowDefaultDisplay =
2433 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2434 ADISPLAY_ID_DEFAULT);
2435 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2436 sp<FakeWindowHandle> windowSecondDisplay =
2437 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2438 SECOND_DISPLAY_ID);
2439 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2440
2441 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2442 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2443
2444 // Set cursor position in window in default display and check that hover enter and move
2445 // events are generated.
2446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2447 injectMotionEvent(mDispatcher,
2448 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2449 AINPUT_SOURCE_MOUSE)
2450 .displayId(ADISPLAY_ID_DEFAULT)
2451 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2452 .x(300)
2453 .y(600))
2454 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002455 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002456
2457 // Remove all windows in secondary display and check that no event happens on window in
2458 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002459 mDispatcher->setInputWindows(
2460 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002461 windowDefaultDisplay->assertNoEvents();
2462
2463 // Move cursor position in window in default display and check that only hover move
2464 // event is generated and not hover enter event.
2465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2466 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2468 injectMotionEvent(mDispatcher,
2469 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2470 AINPUT_SOURCE_MOUSE)
2471 .displayId(ADISPLAY_ID_DEFAULT)
2472 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2473 .x(400)
2474 .y(700))
2475 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002476 windowDefaultDisplay->consumeMotionEvent(
2477 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2478 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002479 windowDefaultDisplay->assertNoEvents();
2480}
2481
Garfield Tan00f511d2019-06-12 16:55:40 -07002482TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002483 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002484
2485 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002486 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002487 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002488 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002489 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002490 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002491
2492 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2493
Arthur Hung72d8dc32020-03-28 00:48:39 +00002494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002495
2496 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2497 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002499 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002500 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002501 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002502 windowRight->assertNoEvents();
2503}
2504
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002505TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002506 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002507 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2508 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002509 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002510
Arthur Hung72d8dc32020-03-28 00:48:39 +00002511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002512 setFocusedWindow(window);
2513
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002514 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002515
2516 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2517 mDispatcher->notifyKey(&keyArgs);
2518
2519 // Window should receive key down event.
2520 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2521
2522 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2523 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002524 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002525 mDispatcher->notifyDeviceReset(&args);
2526 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2527 AKEY_EVENT_FLAG_CANCELED);
2528}
2529
2530TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002531 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002532 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2533 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002534
Arthur Hung72d8dc32020-03-28 00:48:39 +00002535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002536
2537 NotifyMotionArgs motionArgs =
2538 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2539 ADISPLAY_ID_DEFAULT);
2540 mDispatcher->notifyMotion(&motionArgs);
2541
2542 // Window should receive motion down event.
2543 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2544
2545 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2546 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002547 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002548 mDispatcher->notifyDeviceReset(&args);
2549 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2550 0 /*expectedFlags*/);
2551}
2552
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002553TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2554 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002555 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2556 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002557 window->setFocusable(true);
2558
2559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2560 setFocusedWindow(window);
2561
2562 window->consumeFocusEvent(true);
2563
2564 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2565 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2566 const nsecs_t injectTime = keyArgs.eventTime;
2567 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2568 mDispatcher->notifyKey(&keyArgs);
2569 // The dispatching time should be always greater than or equal to intercept key timeout.
2570 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2571 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2572 std::chrono::nanoseconds(interceptKeyTimeout).count());
2573}
2574
2575TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002577 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2578 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002579 window->setFocusable(true);
2580
2581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2582 setFocusedWindow(window);
2583
2584 window->consumeFocusEvent(true);
2585
2586 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2587 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2588 mFakePolicy->setInterceptKeyTimeout(150ms);
2589 mDispatcher->notifyKey(&keyDown);
2590 mDispatcher->notifyKey(&keyUp);
2591
2592 // Window should receive key event immediately when same key up.
2593 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2594 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2595}
2596
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002597/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002598 * Two windows. First is a regular window. Second does not overlap with the first, and has
2599 * WATCH_OUTSIDE_TOUCH.
2600 * Both windows are owned by the same UID.
2601 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
2602 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
2603 */
2604TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
2605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2606 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2607 "First Window", ADISPLAY_ID_DEFAULT);
2608 window->setFrame(Rect{0, 0, 100, 100});
2609
2610 sp<FakeWindowHandle> outsideWindow =
2611 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2612 ADISPLAY_ID_DEFAULT);
2613 outsideWindow->setFrame(Rect{100, 100, 200, 200});
2614 outsideWindow->setWatchOutsideTouch(true);
2615 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
2616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
2617
2618 // Tap on first window.
2619 NotifyMotionArgs motionArgs =
2620 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2621 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
2622 mDispatcher->notifyMotion(&motionArgs);
2623 window->consumeMotionDown();
2624 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
2625 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
2626 outsideWindow->consumeMotionEvent(
2627 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
2628}
2629
2630/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002631 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2632 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2633 * ACTION_OUTSIDE event is sent per gesture.
2634 */
2635TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2636 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2637 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002638 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2639 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002640 window->setWatchOutsideTouch(true);
2641 window->setFrame(Rect{0, 0, 100, 100});
2642 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002643 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2644 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002645 secondWindow->setFrame(Rect{100, 100, 200, 200});
2646 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002647 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2648 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002649 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2651
2652 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2653 NotifyMotionArgs motionArgs =
2654 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2655 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2656 mDispatcher->notifyMotion(&motionArgs);
2657 window->assertNoEvents();
2658 secondWindow->assertNoEvents();
2659
2660 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2661 // Now, `window` should get ACTION_OUTSIDE.
2662 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2663 {PointF{-10, -10}, PointF{105, 105}});
2664 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002665 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
2666 window->consumeMotionEvent(
2667 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002668 secondWindow->consumeMotionDown();
2669 thirdWindow->assertNoEvents();
2670
2671 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2672 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2673 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2674 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2675 mDispatcher->notifyMotion(&motionArgs);
2676 window->assertNoEvents();
2677 secondWindow->consumeMotionMove();
2678 thirdWindow->consumeMotionDown();
2679}
2680
Prabir Pradhan814fe082022-07-22 20:22:18 +00002681TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2682 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002683 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2684 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002685 window->setFocusable(true);
2686
2687 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2688 setFocusedWindow(window);
2689
2690 window->consumeFocusEvent(true);
2691
2692 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2693 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2694 mDispatcher->notifyKey(&keyDown);
2695 mDispatcher->notifyKey(&keyUp);
2696
2697 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2698 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2699
2700 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2701 mDispatcher->onWindowInfosChanged({}, {});
2702
2703 window->consumeFocusEvent(false);
2704
2705 mDispatcher->notifyKey(&keyDown);
2706 mDispatcher->notifyKey(&keyUp);
2707 window->assertNoEvents();
2708}
2709
Arthur Hung96483742022-11-15 03:30:48 +00002710TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2712 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2713 "Fake Window", ADISPLAY_ID_DEFAULT);
2714 // Ensure window is non-split and have some transform.
2715 window->setPreventSplitting(true);
2716 window->setWindowOffset(20, 40);
2717 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2718
2719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2720 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2721 {50, 50}))
2722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2723 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2724
2725 const MotionEvent secondFingerDownEvent =
2726 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2727 .displayId(ADISPLAY_ID_DEFAULT)
2728 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2729 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2730 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2731 .x(-30)
2732 .y(-50))
2733 .build();
2734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2735 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2736 InputEventInjectionSync::WAIT_FOR_RESULT))
2737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2738
2739 const MotionEvent* event = window->consumeMotion();
2740 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2741 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2742 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2743 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2744 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2745}
2746
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002747/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002748 * Ensure the correct coordinate spaces are used by InputDispatcher.
2749 *
2750 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2751 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2752 * space.
2753 */
2754class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2755public:
2756 void SetUp() override {
2757 InputDispatcherTest::SetUp();
2758 mDisplayInfos.clear();
2759 mWindowInfos.clear();
2760 }
2761
2762 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2763 gui::DisplayInfo info;
2764 info.displayId = displayId;
2765 info.transform = transform;
2766 mDisplayInfos.push_back(std::move(info));
2767 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2768 }
2769
2770 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2771 mWindowInfos.push_back(*windowHandle->getInfo());
2772 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2773 }
2774
2775 // Set up a test scenario where the display has a scaled projection and there are two windows
2776 // on the display.
2777 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2778 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2779 // respectively.
2780 ui::Transform displayTransform;
2781 displayTransform.set(2, 0, 0, 4);
2782 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2783
2784 std::shared_ptr<FakeApplicationHandle> application =
2785 std::make_shared<FakeApplicationHandle>();
2786
2787 // Add two windows to the display. Their frames are represented in the display space.
2788 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002789 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2790 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002791 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2792 addWindow(firstWindow);
2793
2794 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002795 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2796 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002797 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2798 addWindow(secondWindow);
2799 return {std::move(firstWindow), std::move(secondWindow)};
2800 }
2801
2802private:
2803 std::vector<gui::DisplayInfo> mDisplayInfos;
2804 std::vector<gui::WindowInfo> mWindowInfos;
2805};
2806
2807TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2808 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2809 // Send down to the first window. The point is represented in the display space. The point is
2810 // selected so that if the hit test was done with the transform applied to it, then it would
2811 // end up in the incorrect window.
2812 NotifyMotionArgs downMotionArgs =
2813 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2814 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2815 mDispatcher->notifyMotion(&downMotionArgs);
2816
2817 firstWindow->consumeMotionDown();
2818 secondWindow->assertNoEvents();
2819}
2820
2821// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2822// the event should be treated as being in the logical display space.
2823TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2824 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2825 // Send down to the first window. The point is represented in the logical display space. The
2826 // point is selected so that if the hit test was done in logical display space, then it would
2827 // end up in the incorrect window.
2828 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2829 PointF{75 * 2, 55 * 4});
2830
2831 firstWindow->consumeMotionDown();
2832 secondWindow->assertNoEvents();
2833}
2834
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002835// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2836// event should be treated as being in the logical display space.
2837TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2838 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2839
2840 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2841 ui::Transform injectedEventTransform;
2842 injectedEventTransform.set(matrix);
2843 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2844 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2845
2846 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2847 .displayId(ADISPLAY_ID_DEFAULT)
2848 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2849 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2850 .x(untransformedPoint.x)
2851 .y(untransformedPoint.y))
2852 .build();
2853 event.transform(matrix);
2854
2855 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2856 InputEventInjectionSync::WAIT_FOR_RESULT);
2857
2858 firstWindow->consumeMotionDown();
2859 secondWindow->assertNoEvents();
2860}
2861
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002862TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2863 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2864
2865 // Send down to the second window.
2866 NotifyMotionArgs downMotionArgs =
2867 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2868 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2869 mDispatcher->notifyMotion(&downMotionArgs);
2870
2871 firstWindow->assertNoEvents();
2872 const MotionEvent* event = secondWindow->consumeMotion();
2873 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2874
2875 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2876 EXPECT_EQ(300, event->getRawX(0));
2877 EXPECT_EQ(880, event->getRawY(0));
2878
2879 // Ensure that the x and y values are in the window's coordinate space.
2880 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2881 // the logical display space. This will be the origin of the window space.
2882 EXPECT_EQ(100, event->getX(0));
2883 EXPECT_EQ(80, event->getY(0));
2884}
2885
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002886using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2887 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002888
2889class TransferTouchFixture : public InputDispatcherTest,
2890 public ::testing::WithParamInterface<TransferFunction> {};
2891
2892TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002893 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002894
2895 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002896 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002897 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2898 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002899 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002900 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002901 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2902 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002903 sp<FakeWindowHandle> wallpaper =
2904 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2905 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002906 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00002907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002908
2909 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002910 NotifyMotionArgs downMotionArgs =
2911 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2912 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002913 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002914
Svet Ganov5d3bc372020-01-26 23:11:07 -08002915 // Only the first window should get the down event
2916 firstWindow->consumeMotionDown();
2917 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002918 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002919
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002920 // Transfer touch to the second window
2921 TransferFunction f = GetParam();
2922 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2923 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002924 // The first window gets cancel and the second gets down
2925 firstWindow->consumeMotionCancel();
2926 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002927 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002928
2929 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002930 NotifyMotionArgs upMotionArgs =
2931 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2932 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002933 mDispatcher->notifyMotion(&upMotionArgs);
2934 // The first window gets no events and the second gets up
2935 firstWindow->assertNoEvents();
2936 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002937 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002938}
2939
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002940/**
2941 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2942 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2943 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2944 * natural to the user.
2945 * In this test, we are sending a pointer to both spy window and first window. We then try to
2946 * transfer touch to the second window. The dispatcher should identify the first window as the
2947 * one that should lose the gesture, and therefore the action should be to move the gesture from
2948 * the first window to the second.
2949 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2950 * the other API, as well.
2951 */
2952TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2953 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2954
2955 // Create a couple of windows + a spy window
2956 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002957 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002958 spyWindow->setTrustedOverlay(true);
2959 spyWindow->setSpy(true);
2960 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002961 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002962 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002963 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002964
2965 // Add the windows to the dispatcher
2966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2967
2968 // Send down to the first window
2969 NotifyMotionArgs downMotionArgs =
2970 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2971 ADISPLAY_ID_DEFAULT);
2972 mDispatcher->notifyMotion(&downMotionArgs);
2973 // Only the first window and spy should get the down event
2974 spyWindow->consumeMotionDown();
2975 firstWindow->consumeMotionDown();
2976
2977 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2978 // if f === 'transferTouch'.
2979 TransferFunction f = GetParam();
2980 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2981 ASSERT_TRUE(success);
2982 // The first window gets cancel and the second gets down
2983 firstWindow->consumeMotionCancel();
2984 secondWindow->consumeMotionDown();
2985
2986 // Send up event to the second window
2987 NotifyMotionArgs upMotionArgs =
2988 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2989 ADISPLAY_ID_DEFAULT);
2990 mDispatcher->notifyMotion(&upMotionArgs);
2991 // The first window gets no events and the second+spy get up
2992 firstWindow->assertNoEvents();
2993 spyWindow->consumeMotionUp();
2994 secondWindow->consumeMotionUp();
2995}
2996
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002997TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002998 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002999
3000 PointF touchPoint = {10, 10};
3001
3002 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003003 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003004 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3005 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003006 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003007 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003008 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3009 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003010 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003011
3012 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003014
3015 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003016 NotifyMotionArgs downMotionArgs =
3017 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3018 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003019 mDispatcher->notifyMotion(&downMotionArgs);
3020 // Only the first window should get the down event
3021 firstWindow->consumeMotionDown();
3022 secondWindow->assertNoEvents();
3023
3024 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003025 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003026 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003027 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003028 mDispatcher->notifyMotion(&pointerDownMotionArgs);
3029 // Only the first window should get the pointer down event
3030 firstWindow->consumeMotionPointerDown(1);
3031 secondWindow->assertNoEvents();
3032
3033 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003034 TransferFunction f = GetParam();
3035 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3036 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003037 // The first window gets cancel and the second gets down and pointer down
3038 firstWindow->consumeMotionCancel();
3039 secondWindow->consumeMotionDown();
3040 secondWindow->consumeMotionPointerDown(1);
3041
3042 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003043 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003044 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003045 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003046 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3047 // The first window gets nothing and the second gets pointer up
3048 firstWindow->assertNoEvents();
3049 secondWindow->consumeMotionPointerUp(1);
3050
3051 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003052 NotifyMotionArgs upMotionArgs =
3053 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3054 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003055 mDispatcher->notifyMotion(&upMotionArgs);
3056 // The first window gets nothing and the second gets up
3057 firstWindow->assertNoEvents();
3058 secondWindow->consumeMotionUp();
3059}
3060
Arthur Hungc539dbb2022-12-08 07:45:36 +00003061TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
3062 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3063
3064 // Create a couple of windows
3065 sp<FakeWindowHandle> firstWindow =
3066 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3067 ADISPLAY_ID_DEFAULT);
3068 firstWindow->setDupTouchToWallpaper(true);
3069 sp<FakeWindowHandle> secondWindow =
3070 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3071 ADISPLAY_ID_DEFAULT);
3072 secondWindow->setDupTouchToWallpaper(true);
3073
3074 sp<FakeWindowHandle> wallpaper1 =
3075 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
3076 wallpaper1->setIsWallpaper(true);
3077
3078 sp<FakeWindowHandle> wallpaper2 =
3079 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
3080 wallpaper2->setIsWallpaper(true);
3081 // Add the windows to the dispatcher
3082 mDispatcher->setInputWindows(
3083 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
3084
3085 // Send down to the first window
3086 NotifyMotionArgs downMotionArgs =
3087 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3088 ADISPLAY_ID_DEFAULT);
3089 mDispatcher->notifyMotion(&downMotionArgs);
3090
3091 // Only the first window should get the down event
3092 firstWindow->consumeMotionDown();
3093 secondWindow->assertNoEvents();
3094 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3095 wallpaper2->assertNoEvents();
3096
3097 // Transfer touch focus to the second window
3098 TransferFunction f = GetParam();
3099 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3100 ASSERT_TRUE(success);
3101
3102 // The first window gets cancel and the second gets down
3103 firstWindow->consumeMotionCancel();
3104 secondWindow->consumeMotionDown();
3105 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3106 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3107
3108 // Send up event to the second window
3109 NotifyMotionArgs upMotionArgs =
3110 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3111 ADISPLAY_ID_DEFAULT);
3112 mDispatcher->notifyMotion(&upMotionArgs);
3113 // The first window gets no events and the second gets up
3114 firstWindow->assertNoEvents();
3115 secondWindow->consumeMotionUp();
3116 wallpaper1->assertNoEvents();
3117 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3118}
3119
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003120// For the cases of single pointer touch and two pointers non-split touch, the api's
3121// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
3122// for the case where there are multiple pointers split across several windows.
3123INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
3124 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003125 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3126 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003127 return dispatcher->transferTouch(destChannelToken,
3128 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003129 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003130 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3131 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003132 return dispatcher->transferTouchFocus(from, to,
3133 false /*isDragAndDrop*/);
3134 }));
3135
Svet Ganov5d3bc372020-01-26 23:11:07 -08003136TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003137 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003138
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003139 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003140 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3141 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003142 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003143
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003144 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003145 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3146 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003147 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003148
3149 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003151
3152 PointF pointInFirst = {300, 200};
3153 PointF pointInSecond = {300, 600};
3154
3155 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003156 NotifyMotionArgs firstDownMotionArgs =
3157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3158 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003159 mDispatcher->notifyMotion(&firstDownMotionArgs);
3160 // Only the first window should get the down event
3161 firstWindow->consumeMotionDown();
3162 secondWindow->assertNoEvents();
3163
3164 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003165 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003166 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003167 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003168 mDispatcher->notifyMotion(&secondDownMotionArgs);
3169 // The first window gets a move and the second a down
3170 firstWindow->consumeMotionMove();
3171 secondWindow->consumeMotionDown();
3172
3173 // Transfer touch focus to the second window
3174 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
3175 // The first window gets cancel and the new gets pointer down (it already saw down)
3176 firstWindow->consumeMotionCancel();
3177 secondWindow->consumeMotionPointerDown(1);
3178
3179 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003180 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003181 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003182 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003183 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3184 // The first window gets nothing and the second gets pointer up
3185 firstWindow->assertNoEvents();
3186 secondWindow->consumeMotionPointerUp(1);
3187
3188 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003189 NotifyMotionArgs upMotionArgs =
3190 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3191 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003192 mDispatcher->notifyMotion(&upMotionArgs);
3193 // The first window gets nothing and the second gets up
3194 firstWindow->assertNoEvents();
3195 secondWindow->consumeMotionUp();
3196}
3197
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003198// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3199// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3200// touch is not supported, so the touch should continue on those windows and the transferred-to
3201// window should get nothing.
3202TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3203 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3204
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003205 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003206 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3207 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003208 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003209
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003210 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003211 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3212 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003213 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003214
3215 // Add the windows to the dispatcher
3216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3217
3218 PointF pointInFirst = {300, 200};
3219 PointF pointInSecond = {300, 600};
3220
3221 // Send down to the first window
3222 NotifyMotionArgs firstDownMotionArgs =
3223 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3224 ADISPLAY_ID_DEFAULT, {pointInFirst});
3225 mDispatcher->notifyMotion(&firstDownMotionArgs);
3226 // Only the first window should get the down event
3227 firstWindow->consumeMotionDown();
3228 secondWindow->assertNoEvents();
3229
3230 // Send down to the second window
3231 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003232 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003233 {pointInFirst, pointInSecond});
3234 mDispatcher->notifyMotion(&secondDownMotionArgs);
3235 // The first window gets a move and the second a down
3236 firstWindow->consumeMotionMove();
3237 secondWindow->consumeMotionDown();
3238
3239 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003240 const bool transferred =
3241 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003242 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3243 ASSERT_FALSE(transferred);
3244 firstWindow->assertNoEvents();
3245 secondWindow->assertNoEvents();
3246
3247 // The rest of the dispatch should proceed as normal
3248 // Send pointer up to the second window
3249 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003250 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003251 {pointInFirst, pointInSecond});
3252 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3253 // The first window gets MOVE and the second gets pointer up
3254 firstWindow->consumeMotionMove();
3255 secondWindow->consumeMotionUp();
3256
3257 // Send up event to the first window
3258 NotifyMotionArgs upMotionArgs =
3259 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3260 ADISPLAY_ID_DEFAULT);
3261 mDispatcher->notifyMotion(&upMotionArgs);
3262 // The first window gets nothing and the second gets up
3263 firstWindow->consumeMotionUp();
3264 secondWindow->assertNoEvents();
3265}
3266
Arthur Hungabbb9d82021-09-01 14:52:30 +00003267// This case will create two windows and one mirrored window on the default display and mirror
3268// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3269// the windows info of second display before default display.
3270TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3271 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3272 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003273 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003274 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003275 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003276 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003277 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003278
3279 sp<FakeWindowHandle> mirrorWindowInPrimary =
3280 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3281 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003282
3283 sp<FakeWindowHandle> firstWindowInSecondary =
3284 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3285 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003286
3287 sp<FakeWindowHandle> secondWindowInSecondary =
3288 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3289 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003290
3291 // Update window info, let it find window handle of second display first.
3292 mDispatcher->setInputWindows(
3293 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3294 {ADISPLAY_ID_DEFAULT,
3295 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3296
3297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3299 {50, 50}))
3300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3301
3302 // Window should receive motion event.
3303 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3304
3305 // Transfer touch focus
3306 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3307 secondWindowInPrimary->getToken()));
3308 // The first window gets cancel.
3309 firstWindowInPrimary->consumeMotionCancel();
3310 secondWindowInPrimary->consumeMotionDown();
3311
3312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3313 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3314 ADISPLAY_ID_DEFAULT, {150, 50}))
3315 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3316 firstWindowInPrimary->assertNoEvents();
3317 secondWindowInPrimary->consumeMotionMove();
3318
3319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3320 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3321 {150, 50}))
3322 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3323 firstWindowInPrimary->assertNoEvents();
3324 secondWindowInPrimary->consumeMotionUp();
3325}
3326
3327// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3328// 'transferTouch' api.
3329TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3330 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3331 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003332 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003333 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003334 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003335 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003336 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003337
3338 sp<FakeWindowHandle> mirrorWindowInPrimary =
3339 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3340 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003341
3342 sp<FakeWindowHandle> firstWindowInSecondary =
3343 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3344 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003345
3346 sp<FakeWindowHandle> secondWindowInSecondary =
3347 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3348 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003349
3350 // Update window info, let it find window handle of second display first.
3351 mDispatcher->setInputWindows(
3352 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3353 {ADISPLAY_ID_DEFAULT,
3354 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3355
3356 // Touch on second display.
3357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3358 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3359 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3360
3361 // Window should receive motion event.
3362 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3363
3364 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003365 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003366
3367 // The first window gets cancel.
3368 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3369 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3370
3371 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3372 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3373 SECOND_DISPLAY_ID, {150, 50}))
3374 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3375 firstWindowInPrimary->assertNoEvents();
3376 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3377
3378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3379 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3380 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3381 firstWindowInPrimary->assertNoEvents();
3382 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3383}
3384
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003385TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003386 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003387 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3388 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003389
Vishnu Nair47074b82020-08-14 11:54:47 -07003390 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003392 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003393
3394 window->consumeFocusEvent(true);
3395
3396 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3397 mDispatcher->notifyKey(&keyArgs);
3398
3399 // Window should receive key down event.
3400 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3401}
3402
3403TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003404 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003405 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3406 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003407
Arthur Hung72d8dc32020-03-28 00:48:39 +00003408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003409
3410 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3411 mDispatcher->notifyKey(&keyArgs);
3412 mDispatcher->waitForIdle();
3413
3414 window->assertNoEvents();
3415}
3416
3417// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3418TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003419 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003420 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3421 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003422
Arthur Hung72d8dc32020-03-28 00:48:39 +00003423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003424
3425 // Send key
3426 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3427 mDispatcher->notifyKey(&keyArgs);
3428 // Send motion
3429 NotifyMotionArgs motionArgs =
3430 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3431 ADISPLAY_ID_DEFAULT);
3432 mDispatcher->notifyMotion(&motionArgs);
3433
3434 // Window should receive only the motion event
3435 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3436 window->assertNoEvents(); // Key event or focus event will not be received
3437}
3438
arthurhungea3f4fc2020-12-21 23:18:53 +08003439TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3441
arthurhungea3f4fc2020-12-21 23:18:53 +08003442 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003443 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3444 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003445 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003446
arthurhungea3f4fc2020-12-21 23:18:53 +08003447 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003448 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3449 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003450 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003451
3452 // Add the windows to the dispatcher
3453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3454
3455 PointF pointInFirst = {300, 200};
3456 PointF pointInSecond = {300, 600};
3457
3458 // Send down to the first window
3459 NotifyMotionArgs firstDownMotionArgs =
3460 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3461 ADISPLAY_ID_DEFAULT, {pointInFirst});
3462 mDispatcher->notifyMotion(&firstDownMotionArgs);
3463 // Only the first window should get the down event
3464 firstWindow->consumeMotionDown();
3465 secondWindow->assertNoEvents();
3466
3467 // Send down to the second window
3468 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003469 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003470 {pointInFirst, pointInSecond});
3471 mDispatcher->notifyMotion(&secondDownMotionArgs);
3472 // The first window gets a move and the second a down
3473 firstWindow->consumeMotionMove();
3474 secondWindow->consumeMotionDown();
3475
3476 // Send pointer cancel to the second window
3477 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003478 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003479 {pointInFirst, pointInSecond});
3480 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3481 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3482 // The first window gets move and the second gets cancel.
3483 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3484 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3485
3486 // Send up event.
3487 NotifyMotionArgs upMotionArgs =
3488 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3489 ADISPLAY_ID_DEFAULT);
3490 mDispatcher->notifyMotion(&upMotionArgs);
3491 // The first window gets up and the second gets nothing.
3492 firstWindow->consumeMotionUp();
3493 secondWindow->assertNoEvents();
3494}
3495
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003496TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3497 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3498
3499 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003500 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3502 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3503 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3504 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3505
3506 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3507 window->assertNoEvents();
3508 mDispatcher->waitForIdle();
3509}
3510
chaviwd1c23182019-12-20 18:44:56 -08003511class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003512public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003513 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003514 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003515 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003516 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003517 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003518 }
3519
chaviwd1c23182019-12-20 18:44:56 -08003520 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3521
3522 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3523 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3524 expectedDisplayId, expectedFlags);
3525 }
3526
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003527 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3528
3529 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3530
chaviwd1c23182019-12-20 18:44:56 -08003531 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3532 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3533 expectedDisplayId, expectedFlags);
3534 }
3535
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003536 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3537 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3538 expectedDisplayId, expectedFlags);
3539 }
3540
chaviwd1c23182019-12-20 18:44:56 -08003541 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3542 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3543 expectedDisplayId, expectedFlags);
3544 }
3545
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003546 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3547 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3548 expectedDisplayId, expectedFlags);
3549 }
3550
Arthur Hungfbfa5722021-11-16 02:45:54 +00003551 void consumeMotionPointerDown(int32_t pointerIdx) {
3552 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3553 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3554 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3555 0 /*expectedFlags*/);
3556 }
3557
Evan Rosky84f07f02021-04-16 10:42:42 -07003558 MotionEvent* consumeMotion() {
3559 InputEvent* event = mInputReceiver->consume();
3560 if (!event) {
3561 ADD_FAILURE() << "No event was produced";
3562 return nullptr;
3563 }
3564 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3565 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3566 return nullptr;
3567 }
3568 return static_cast<MotionEvent*>(event);
3569 }
3570
chaviwd1c23182019-12-20 18:44:56 -08003571 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3572
3573private:
3574 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003575};
3576
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003577using InputDispatcherMonitorTest = InputDispatcherTest;
3578
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003579/**
3580 * Two entities that receive touch: A window, and a global monitor.
3581 * The touch goes to the window, and then the window disappears.
3582 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3583 * for the monitor, as well.
3584 * 1. foregroundWindow
3585 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3586 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003587TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003588 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3589 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003590 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003591
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003592 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003593
3594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3595 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3596 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3597 {100, 200}))
3598 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3599
3600 // Both the foreground window and the global monitor should receive the touch down
3601 window->consumeMotionDown();
3602 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3603
3604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3605 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3606 ADISPLAY_ID_DEFAULT, {110, 200}))
3607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3608
3609 window->consumeMotionMove();
3610 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3611
3612 // Now the foreground window goes away
3613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3614 window->consumeMotionCancel();
3615 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3616
3617 // If more events come in, there will be no more foreground window to send them to. This will
3618 // cause a cancel for the monitor, as well.
3619 ASSERT_EQ(InputEventInjectionResult::FAILED,
3620 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3621 ADISPLAY_ID_DEFAULT, {120, 200}))
3622 << "Injection should fail because the window was removed";
3623 window->assertNoEvents();
3624 // Global monitor now gets the cancel
3625 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3626}
3627
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003628TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003630 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3631 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003633
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003634 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003635
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003637 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003638 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003639 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003640 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003641}
3642
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003643TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3644 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003645
Chris Yea209fde2020-07-22 13:54:51 -07003646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003647 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3648 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003650
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003652 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003654 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003655 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003656
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003657 // Pilfer pointers from the monitor.
3658 // This should not do anything and the window should continue to receive events.
3659 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003660
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003662 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3663 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003665
3666 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3667 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003668}
3669
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003670TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003671 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003672 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3673 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3675 window->setWindowOffset(20, 40);
3676 window->setWindowTransform(0, 1, -1, 0);
3677
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003678 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003679
3680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3681 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3683 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3684 MotionEvent* event = monitor.consumeMotion();
3685 // Even though window has transform, gesture monitor must not.
3686 ASSERT_EQ(ui::Transform(), event->getTransform());
3687}
3688
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003689TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003691 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003692
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003693 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003694 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003695 << "Injection should fail if there is a monitor, but no touchable window";
3696 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003697}
3698
chaviw81e2bb92019-12-18 15:03:51 -08003699TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003700 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003701 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3702 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003703
Arthur Hung72d8dc32020-03-28 00:48:39 +00003704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003705
3706 NotifyMotionArgs motionArgs =
3707 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3708 ADISPLAY_ID_DEFAULT);
3709
3710 mDispatcher->notifyMotion(&motionArgs);
3711 // Window should receive motion down event.
3712 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3713
3714 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003715 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003716 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3717 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3718 motionArgs.pointerCoords[0].getX() - 10);
3719
3720 mDispatcher->notifyMotion(&motionArgs);
3721 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3722 0 /*expectedFlags*/);
3723}
3724
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003725/**
3726 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3727 * the device default right away. In the test scenario, we check both the default value,
3728 * and the action of enabling / disabling.
3729 */
3730TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003731 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003732 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3733 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003734 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003735
3736 // Set focused application.
3737 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003738 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003739
3740 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003742 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003743 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3744
3745 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003746 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003748 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3749
3750 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003751 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003752 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003753 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003754 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003756 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003757 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3758
3759 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003760 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003762 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3763
3764 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003765 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003766 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003767 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003768 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003770 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003771 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3772
3773 window->assertNoEvents();
3774}
3775
Gang Wange9087892020-01-07 12:17:14 -05003776TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003777 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003778 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3779 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003780
3781 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003782 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003783
Arthur Hung72d8dc32020-03-28 00:48:39 +00003784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003785 setFocusedWindow(window);
3786
Gang Wange9087892020-01-07 12:17:14 -05003787 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3788
3789 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3790 mDispatcher->notifyKey(&keyArgs);
3791
3792 InputEvent* event = window->consume();
3793 ASSERT_NE(event, nullptr);
3794
3795 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3796 ASSERT_NE(verified, nullptr);
3797 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3798
3799 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3800 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3801 ASSERT_EQ(keyArgs.source, verified->source);
3802 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3803
3804 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3805
3806 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003807 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003808 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003809 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3810 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3811 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3812 ASSERT_EQ(0, verifiedKey.repeatCount);
3813}
3814
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003815TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003816 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003817 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3818 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003819
3820 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3821
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003822 ui::Transform transform;
3823 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3824
3825 gui::DisplayInfo displayInfo;
3826 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3827 displayInfo.transform = transform;
3828
3829 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003830
3831 NotifyMotionArgs motionArgs =
3832 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3833 ADISPLAY_ID_DEFAULT);
3834 mDispatcher->notifyMotion(&motionArgs);
3835
3836 InputEvent* event = window->consume();
3837 ASSERT_NE(event, nullptr);
3838
3839 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3840 ASSERT_NE(verified, nullptr);
3841 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3842
3843 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3844 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3845 EXPECT_EQ(motionArgs.source, verified->source);
3846 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3847
3848 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3849
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003850 const vec2 rawXY =
3851 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3852 motionArgs.pointerCoords[0].getXYValue());
3853 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3854 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003855 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003856 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003857 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003858 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3859 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3860}
3861
chaviw09c8d2d2020-08-24 15:48:26 -07003862/**
3863 * Ensure that separate calls to sign the same data are generating the same key.
3864 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3865 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3866 * tests.
3867 */
3868TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3869 KeyEvent event = getTestKeyEvent();
3870 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3871
3872 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3873 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3874 ASSERT_EQ(hmac1, hmac2);
3875}
3876
3877/**
3878 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3879 */
3880TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3881 KeyEvent event = getTestKeyEvent();
3882 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3883 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3884
3885 verifiedEvent.deviceId += 1;
3886 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3887
3888 verifiedEvent.source += 1;
3889 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3890
3891 verifiedEvent.eventTimeNanos += 1;
3892 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3893
3894 verifiedEvent.displayId += 1;
3895 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3896
3897 verifiedEvent.action += 1;
3898 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3899
3900 verifiedEvent.downTimeNanos += 1;
3901 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3902
3903 verifiedEvent.flags += 1;
3904 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3905
3906 verifiedEvent.keyCode += 1;
3907 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3908
3909 verifiedEvent.scanCode += 1;
3910 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3911
3912 verifiedEvent.metaState += 1;
3913 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3914
3915 verifiedEvent.repeatCount += 1;
3916 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3917}
3918
Vishnu Nair958da932020-08-21 17:12:37 -07003919TEST_F(InputDispatcherTest, SetFocusedWindow) {
3920 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3921 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003922 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003923 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003924 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003925 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3926
3927 // Top window is also focusable but is not granted focus.
3928 windowTop->setFocusable(true);
3929 windowSecond->setFocusable(true);
3930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3931 setFocusedWindow(windowSecond);
3932
3933 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3935 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003936
3937 // Focused window should receive event.
3938 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3939 windowTop->assertNoEvents();
3940}
3941
3942TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3943 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3944 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003945 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003946 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3947
3948 window->setFocusable(true);
3949 // Release channel for window is no longer valid.
3950 window->releaseChannel();
3951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3952 setFocusedWindow(window);
3953
3954 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003955 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3956 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003957
3958 // window channel is invalid, so it should not receive any input event.
3959 window->assertNoEvents();
3960}
3961
3962TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3963 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3964 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003965 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003966 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003967 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3968
Vishnu Nair958da932020-08-21 17:12:37 -07003969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3970 setFocusedWindow(window);
3971
3972 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003973 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3974 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003975
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003976 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003977 window->assertNoEvents();
3978}
3979
3980TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3981 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3982 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003983 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003984 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003985 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003986 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3987
3988 windowTop->setFocusable(true);
3989 windowSecond->setFocusable(true);
3990 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3991 setFocusedWindow(windowTop);
3992 windowTop->consumeFocusEvent(true);
3993
3994 setFocusedWindow(windowSecond, windowTop);
3995 windowSecond->consumeFocusEvent(true);
3996 windowTop->consumeFocusEvent(false);
3997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3999 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004000
4001 // Focused window should receive event.
4002 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4003}
4004
4005TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
4006 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4007 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004008 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004009 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004010 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004011 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4012
4013 windowTop->setFocusable(true);
4014 windowSecond->setFocusable(true);
4015 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4016 setFocusedWindow(windowSecond, windowTop);
4017
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004018 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4019 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004020
4021 // Event should be dropped.
4022 windowTop->assertNoEvents();
4023 windowSecond->assertNoEvents();
4024}
4025
4026TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
4027 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4028 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004029 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004030 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004031 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
4032 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004033 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4034
4035 window->setFocusable(true);
4036 previousFocusedWindow->setFocusable(true);
4037 window->setVisible(false);
4038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
4039 setFocusedWindow(previousFocusedWindow);
4040 previousFocusedWindow->consumeFocusEvent(true);
4041
4042 // Requesting focus on invisible window takes focus from currently focused window.
4043 setFocusedWindow(window);
4044 previousFocusedWindow->consumeFocusEvent(false);
4045
4046 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004048 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004049 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004050
4051 // Window does not get focus event or key down.
4052 window->assertNoEvents();
4053
4054 // Window becomes visible.
4055 window->setVisible(true);
4056 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4057
4058 // Window receives focus event.
4059 window->consumeFocusEvent(true);
4060 // Focused window receives key down.
4061 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4062}
4063
Vishnu Nair599f1412021-06-21 10:39:58 -07004064TEST_F(InputDispatcherTest, DisplayRemoved) {
4065 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4066 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004067 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07004068 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4069
4070 // window is granted focus.
4071 window->setFocusable(true);
4072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4073 setFocusedWindow(window);
4074 window->consumeFocusEvent(true);
4075
4076 // When a display is removed window loses focus.
4077 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
4078 window->consumeFocusEvent(false);
4079}
4080
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004081/**
4082 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
4083 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
4084 * of the 'slipperyEnterWindow'.
4085 *
4086 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
4087 * a way so that the touched location is no longer covered by the top window.
4088 *
4089 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
4090 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
4091 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
4092 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
4093 * with ACTION_DOWN).
4094 * Thus, the touch has been transferred from the top window into the bottom window, because the top
4095 * window moved itself away from the touched location and had Flag::SLIPPERY.
4096 *
4097 * Even though the top window moved away from the touched location, it is still obscuring the bottom
4098 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
4099 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
4100 *
4101 * In this test, we ensure that the event received by the bottom window has
4102 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
4103 */
4104TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004105 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
4106 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004107
4108 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4109 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4110
4111 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004112 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004113 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004114 // Make sure this one overlaps the bottom window
4115 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
4116 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
4117 // one. Windows with the same owner are not considered to be occluding each other.
4118 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
4119
4120 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004121 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004122 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
4123
4124 mDispatcher->setInputWindows(
4125 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4126
4127 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
4128 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4129 ADISPLAY_ID_DEFAULT, {{50, 50}});
4130 mDispatcher->notifyMotion(&args);
4131 slipperyExitWindow->consumeMotionDown();
4132 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
4133 mDispatcher->setInputWindows(
4134 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4135
4136 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4137 ADISPLAY_ID_DEFAULT, {{51, 51}});
4138 mDispatcher->notifyMotion(&args);
4139
4140 slipperyExitWindow->consumeMotionCancel();
4141
4142 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
4143 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
4144}
4145
Garfield Tan1c7bc862020-01-28 13:24:04 -08004146class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
4147protected:
4148 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
4149 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
4150
Chris Yea209fde2020-07-22 13:54:51 -07004151 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004152 sp<FakeWindowHandle> mWindow;
4153
4154 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004155 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08004156 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004157 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004158 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
4159 ASSERT_EQ(OK, mDispatcher->start());
4160
4161 setUpWindow();
4162 }
4163
4164 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07004165 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004166 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004167
Vishnu Nair47074b82020-08-14 11:54:47 -07004168 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004170 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004171 mWindow->consumeFocusEvent(true);
4172 }
4173
Chris Ye2ad95392020-09-01 13:44:44 -07004174 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004175 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004176 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004177 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
4178 mDispatcher->notifyKey(&keyArgs);
4179
4180 // Window should receive key down event.
4181 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4182 }
4183
4184 void expectKeyRepeatOnce(int32_t repeatCount) {
4185 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
4186 InputEvent* repeatEvent = mWindow->consume();
4187 ASSERT_NE(nullptr, repeatEvent);
4188
4189 uint32_t eventType = repeatEvent->getType();
4190 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4191
4192 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4193 uint32_t eventAction = repeatKeyEvent->getAction();
4194 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4195 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4196 }
4197
Chris Ye2ad95392020-09-01 13:44:44 -07004198 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004199 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004200 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004201 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4202 mDispatcher->notifyKey(&keyArgs);
4203
4204 // Window should receive key down event.
4205 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
4206 0 /*expectedFlags*/);
4207 }
4208};
4209
4210TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07004211 sendAndConsumeKeyDown(1 /* deviceId */);
4212 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4213 expectKeyRepeatOnce(repeatCount);
4214 }
4215}
4216
4217TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
4218 sendAndConsumeKeyDown(1 /* deviceId */);
4219 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4220 expectKeyRepeatOnce(repeatCount);
4221 }
4222 sendAndConsumeKeyDown(2 /* deviceId */);
4223 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004224 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4225 expectKeyRepeatOnce(repeatCount);
4226 }
4227}
4228
4229TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07004230 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004231 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07004232 sendAndConsumeKeyUp(1 /* deviceId */);
4233 mWindow->assertNoEvents();
4234}
4235
4236TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
4237 sendAndConsumeKeyDown(1 /* deviceId */);
4238 expectKeyRepeatOnce(1 /*repeatCount*/);
4239 sendAndConsumeKeyDown(2 /* deviceId */);
4240 expectKeyRepeatOnce(1 /*repeatCount*/);
4241 // Stale key up from device 1.
4242 sendAndConsumeKeyUp(1 /* deviceId */);
4243 // Device 2 is still down, keep repeating
4244 expectKeyRepeatOnce(2 /*repeatCount*/);
4245 expectKeyRepeatOnce(3 /*repeatCount*/);
4246 // Device 2 key up
4247 sendAndConsumeKeyUp(2 /* deviceId */);
4248 mWindow->assertNoEvents();
4249}
4250
4251TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
4252 sendAndConsumeKeyDown(1 /* deviceId */);
4253 expectKeyRepeatOnce(1 /*repeatCount*/);
4254 sendAndConsumeKeyDown(2 /* deviceId */);
4255 expectKeyRepeatOnce(1 /*repeatCount*/);
4256 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
4257 sendAndConsumeKeyUp(2 /* deviceId */);
4258 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004259 mWindow->assertNoEvents();
4260}
4261
liushenxiang42232912021-05-21 20:24:09 +08004262TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4263 sendAndConsumeKeyDown(DEVICE_ID);
4264 expectKeyRepeatOnce(1 /*repeatCount*/);
4265 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
4266 mDispatcher->notifyDeviceReset(&args);
4267 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4268 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4269 mWindow->assertNoEvents();
4270}
4271
Garfield Tan1c7bc862020-01-28 13:24:04 -08004272TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004273 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004274 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4275 InputEvent* repeatEvent = mWindow->consume();
4276 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4277 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4278 IdGenerator::getSource(repeatEvent->getId()));
4279 }
4280}
4281
4282TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004283 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004284
4285 std::unordered_set<int32_t> idSet;
4286 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4287 InputEvent* repeatEvent = mWindow->consume();
4288 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4289 int32_t id = repeatEvent->getId();
4290 EXPECT_EQ(idSet.end(), idSet.find(id));
4291 idSet.insert(id);
4292 }
4293}
4294
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004295/* Test InputDispatcher for MultiDisplay */
4296class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4297public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004298 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004299 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004300
Chris Yea209fde2020-07-22 13:54:51 -07004301 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004302 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004303 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004304
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004305 // Set focus window for primary display, but focused display would be second one.
4306 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004307 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004309 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004310 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004311
Chris Yea209fde2020-07-22 13:54:51 -07004312 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004313 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004314 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004315 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004316 // Set focus display to second one.
4317 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4318 // Set focus window for second display.
4319 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004320 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004321 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004322 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004323 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004324 }
4325
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004326 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004327 InputDispatcherTest::TearDown();
4328
Chris Yea209fde2020-07-22 13:54:51 -07004329 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004330 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004331 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004332 windowInSecondary.clear();
4333 }
4334
4335protected:
Chris Yea209fde2020-07-22 13:54:51 -07004336 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004337 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004338 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004339 sp<FakeWindowHandle> windowInSecondary;
4340};
4341
4342TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4343 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4345 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4346 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004347 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004348 windowInSecondary->assertNoEvents();
4349
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004350 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4352 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4353 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004354 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004355 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004356}
4357
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004358TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004359 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4361 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004362 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004363 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004364 windowInSecondary->assertNoEvents();
4365
4366 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004369 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004370 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004371
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004372 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004373 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004374
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004376 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4377 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004378
4379 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004380 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004382 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004383 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004384 windowInSecondary->assertNoEvents();
4385}
4386
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004387// Test per-display input monitors for motion event.
4388TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004389 FakeMonitorReceiver monitorInPrimary =
4390 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4391 FakeMonitorReceiver monitorInSecondary =
4392 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004393
4394 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4396 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4397 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004398 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004399 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004400 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004401 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004402
4403 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4405 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004407 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004408 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004409 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004410 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004411
4412 // Test inject a non-pointer motion event.
4413 // If specific a display, it will dispatch to the focused window of particular display,
4414 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4416 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004418 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004419 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004420 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004421 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004422}
4423
4424// Test per-display input monitors for key event.
4425TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004426 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004427 FakeMonitorReceiver monitorInPrimary =
4428 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4429 FakeMonitorReceiver monitorInSecondary =
4430 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004431
4432 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004433 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4434 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004435 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004436 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004437 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004438 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004439}
4440
Vishnu Nair958da932020-08-21 17:12:37 -07004441TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4442 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004443 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004444 secondWindowInPrimary->setFocusable(true);
4445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4446 setFocusedWindow(secondWindowInPrimary);
4447 windowInPrimary->consumeFocusEvent(false);
4448 secondWindowInPrimary->consumeFocusEvent(true);
4449
4450 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4452 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004453 windowInPrimary->assertNoEvents();
4454 windowInSecondary->assertNoEvents();
4455 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4456}
4457
Arthur Hungdfd528e2021-12-08 13:23:04 +00004458TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4459 FakeMonitorReceiver monitorInPrimary =
4460 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4461 FakeMonitorReceiver monitorInSecondary =
4462 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4463
4464 // Test touch down on primary display.
4465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4466 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4468 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4469 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4470
4471 // Test touch down on second display.
4472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4475 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4476 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4477
4478 // Trigger cancel touch.
4479 mDispatcher->cancelCurrentTouch();
4480 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4481 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4482 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4483 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4484
4485 // Test inject a move motion event, no window/monitor should receive the event.
4486 ASSERT_EQ(InputEventInjectionResult::FAILED,
4487 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4488 ADISPLAY_ID_DEFAULT, {110, 200}))
4489 << "Inject motion event should return InputEventInjectionResult::FAILED";
4490 windowInPrimary->assertNoEvents();
4491 monitorInPrimary.assertNoEvents();
4492
4493 ASSERT_EQ(InputEventInjectionResult::FAILED,
4494 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4495 SECOND_DISPLAY_ID, {110, 200}))
4496 << "Inject motion event should return InputEventInjectionResult::FAILED";
4497 windowInSecondary->assertNoEvents();
4498 monitorInSecondary.assertNoEvents();
4499}
4500
Jackal Guof9696682018-10-05 12:23:23 +08004501class InputFilterTest : public InputDispatcherTest {
4502protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004503 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4504 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004505 NotifyMotionArgs motionArgs;
4506
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004507 motionArgs =
4508 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004509 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004510 motionArgs =
4511 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004512 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004513 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004514 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004515 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4516 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004517 } else {
4518 mFakePolicy->assertFilterInputEventWasNotCalled();
4519 }
4520 }
4521
4522 void testNotifyKey(bool expectToBeFiltered) {
4523 NotifyKeyArgs keyArgs;
4524
4525 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4526 mDispatcher->notifyKey(&keyArgs);
4527 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4528 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004529 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004530
4531 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004532 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004533 } else {
4534 mFakePolicy->assertFilterInputEventWasNotCalled();
4535 }
4536 }
4537};
4538
4539// Test InputFilter for MotionEvent
4540TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4541 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4542 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4543 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4544
4545 // Enable InputFilter
4546 mDispatcher->setInputFilterEnabled(true);
4547 // Test touch on both primary and second display, and check if both events are filtered.
4548 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4549 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4550
4551 // Disable InputFilter
4552 mDispatcher->setInputFilterEnabled(false);
4553 // Test touch on both primary and second display, and check if both events aren't filtered.
4554 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4555 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4556}
4557
4558// Test InputFilter for KeyEvent
4559TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4560 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4561 testNotifyKey(/*expectToBeFiltered*/ false);
4562
4563 // Enable InputFilter
4564 mDispatcher->setInputFilterEnabled(true);
4565 // Send a key event, and check if it is filtered.
4566 testNotifyKey(/*expectToBeFiltered*/ true);
4567
4568 // Disable InputFilter
4569 mDispatcher->setInputFilterEnabled(false);
4570 // Send a key event, and check if it isn't filtered.
4571 testNotifyKey(/*expectToBeFiltered*/ false);
4572}
4573
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004574// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4575// logical display coordinate space.
4576TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4577 ui::Transform firstDisplayTransform;
4578 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4579 ui::Transform secondDisplayTransform;
4580 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4581
4582 std::vector<gui::DisplayInfo> displayInfos(2);
4583 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4584 displayInfos[0].transform = firstDisplayTransform;
4585 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4586 displayInfos[1].transform = secondDisplayTransform;
4587
4588 mDispatcher->onWindowInfosChanged({}, displayInfos);
4589
4590 // Enable InputFilter
4591 mDispatcher->setInputFilterEnabled(true);
4592
4593 // Ensure the correct transforms are used for the displays.
4594 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4595 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4596}
4597
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4599protected:
4600 virtual void SetUp() override {
4601 InputDispatcherTest::SetUp();
4602
4603 /**
4604 * We don't need to enable input filter to test the injected event policy, but we enabled it
4605 * here to make the tests more realistic, since this policy only matters when inputfilter is
4606 * on.
4607 */
4608 mDispatcher->setInputFilterEnabled(true);
4609
4610 std::shared_ptr<InputApplicationHandle> application =
4611 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004612 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4613 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004614
4615 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4616 mWindow->setFocusable(true);
4617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4618 setFocusedWindow(mWindow);
4619 mWindow->consumeFocusEvent(true);
4620 }
4621
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004622 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4623 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004624 KeyEvent event;
4625
4626 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4627 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4628 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4629 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4630 const int32_t additionalPolicyFlags =
4631 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004633 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004634 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4635 policyFlags | additionalPolicyFlags));
4636
4637 InputEvent* received = mWindow->consume();
4638 ASSERT_NE(nullptr, received);
4639 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004640 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4641 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4642 ASSERT_EQ(flags, keyEvent.getFlags());
4643 }
4644
4645 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4646 int32_t flags) {
4647 MotionEvent event;
4648 PointerProperties pointerProperties[1];
4649 PointerCoords pointerCoords[1];
4650 pointerProperties[0].clear();
4651 pointerProperties[0].id = 0;
4652 pointerCoords[0].clear();
4653 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4654 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4655
4656 ui::Transform identityTransform;
4657 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4658 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4659 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4660 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4661 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004663 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004664 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4665
4666 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004668 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004669 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4670 policyFlags | additionalPolicyFlags));
4671
4672 InputEvent* received = mWindow->consume();
4673 ASSERT_NE(nullptr, received);
4674 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4675 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4676 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4677 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004678 }
4679
4680private:
4681 sp<FakeWindowHandle> mWindow;
4682};
4683
4684TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004685 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4686 // filter. Without it, the event will no different from a regularly injected event, and the
4687 // injected device id will be overwritten.
4688 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4689 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004690}
4691
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004692TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004693 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004694 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4695 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4696}
4697
4698TEST_F(InputFilterInjectionPolicyTest,
4699 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4700 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4701 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4702 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004703}
4704
4705TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4706 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004707 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004708}
4709
chaviwfd6d3512019-03-25 13:23:49 -07004710class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004711 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004712 InputDispatcherTest::SetUp();
4713
Chris Yea209fde2020-07-22 13:54:51 -07004714 std::shared_ptr<FakeApplicationHandle> application =
4715 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004716 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004717 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004718 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004719
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004720 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004721 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004722 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004723
4724 // Set focused application.
4725 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004726 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004727
4728 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004730 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004731 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004732 }
4733
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004734 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004735 InputDispatcherTest::TearDown();
4736
4737 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004738 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004739 }
4740
4741protected:
4742 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004743 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004744 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004745};
4746
4747// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4748// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4749// the onPointerDownOutsideFocus callback.
4750TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004752 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4753 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004754 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004755 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004756
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004757 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004758 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4759}
4760
4761// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4762// DOWN on the window that doesn't have focus. Ensure no window received the
4763// onPointerDownOutsideFocus callback.
4764TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004766 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
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
4774// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4775// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4776TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4778 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004779 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004780 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004781
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004782 ASSERT_TRUE(mDispatcher->waitForIdle());
4783 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004784}
4785
4786// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4787// DOWN on the window that already has focus. Ensure no window received the
4788// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004789TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004791 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004792 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004794 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004795
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004796 ASSERT_TRUE(mDispatcher->waitForIdle());
4797 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004798}
4799
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004800// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4801// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4802TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4803 const MotionEvent event =
4804 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4805 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4806 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4807 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4808 .build();
4809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4811 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4812
4813 ASSERT_TRUE(mDispatcher->waitForIdle());
4814 mFakePolicy->assertOnPointerDownWasNotCalled();
4815 // Ensure that the unfocused window did not receive any FOCUS events.
4816 mUnfocusedWindow->assertNoEvents();
4817}
4818
chaviwaf87b3e2019-10-01 16:59:28 -07004819// These tests ensures we can send touch events to a single client when there are multiple input
4820// windows that point to the same client token.
4821class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4822 virtual void SetUp() override {
4823 InputDispatcherTest::SetUp();
4824
Chris Yea209fde2020-07-22 13:54:51 -07004825 std::shared_ptr<FakeApplicationHandle> application =
4826 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004827 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4828 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004829 mWindow1->setFrame(Rect(0, 0, 100, 100));
4830
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004831 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4832 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004833 mWindow2->setFrame(Rect(100, 100, 200, 200));
4834
Arthur Hung72d8dc32020-03-28 00:48:39 +00004835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004836 }
4837
4838protected:
4839 sp<FakeWindowHandle> mWindow1;
4840 sp<FakeWindowHandle> mWindow2;
4841
4842 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004843 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004844 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4845 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004846 }
4847
4848 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4849 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004850 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004851 InputEvent* event = window->consume();
4852
4853 ASSERT_NE(nullptr, event) << name.c_str()
4854 << ": consumer should have returned non-NULL event.";
4855
4856 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4857 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4858 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4859
4860 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004861 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08004862 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07004863
4864 for (size_t i = 0; i < points.size(); i++) {
4865 float expectedX = points[i].x;
4866 float expectedY = points[i].y;
4867
4868 EXPECT_EQ(expectedX, motionEvent.getX(i))
4869 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4870 << ", got " << motionEvent.getX(i);
4871 EXPECT_EQ(expectedY, motionEvent.getY(i))
4872 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4873 << ", got " << motionEvent.getY(i);
4874 }
4875 }
chaviw9eaa22c2020-07-01 16:21:27 -07004876
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004877 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004878 std::vector<PointF> expectedPoints) {
4879 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4880 ADISPLAY_ID_DEFAULT, touchedPoints);
4881 mDispatcher->notifyMotion(&motionArgs);
4882
4883 // Always consume from window1 since it's the window that has the InputReceiver
4884 consumeMotionEvent(mWindow1, action, expectedPoints);
4885 }
chaviwaf87b3e2019-10-01 16:59:28 -07004886};
4887
4888TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4889 // Touch Window 1
4890 PointF touchedPoint = {10, 10};
4891 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004892 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004893
4894 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004895 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004896
4897 // Touch Window 2
4898 touchedPoint = {150, 150};
4899 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004900 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004901}
4902
chaviw9eaa22c2020-07-01 16:21:27 -07004903TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4904 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004905 mWindow2->setWindowScale(0.5f, 0.5f);
4906
4907 // Touch Window 1
4908 PointF touchedPoint = {10, 10};
4909 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004910 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004911 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004912 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004913
4914 // Touch Window 2
4915 touchedPoint = {150, 150};
4916 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004917 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4918 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004919
chaviw9eaa22c2020-07-01 16:21:27 -07004920 // Update the transform so rotation is set
4921 mWindow2->setWindowTransform(0, -1, 1, 0);
4922 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4923 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004924}
4925
chaviw9eaa22c2020-07-01 16:21:27 -07004926TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004927 mWindow2->setWindowScale(0.5f, 0.5f);
4928
4929 // Touch Window 1
4930 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4931 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004932 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004933
4934 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004935 touchedPoints.push_back(PointF{150, 150});
4936 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004937 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004938
chaviw9eaa22c2020-07-01 16:21:27 -07004939 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004940 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004941 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004942
chaviw9eaa22c2020-07-01 16:21:27 -07004943 // Update the transform so rotation is set for Window 2
4944 mWindow2->setWindowTransform(0, -1, 1, 0);
4945 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004946 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004947}
4948
chaviw9eaa22c2020-07-01 16:21:27 -07004949TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004950 mWindow2->setWindowScale(0.5f, 0.5f);
4951
4952 // Touch Window 1
4953 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4954 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004955 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004956
4957 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004958 touchedPoints.push_back(PointF{150, 150});
4959 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004960
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004961 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004962
4963 // Move both windows
4964 touchedPoints = {{20, 20}, {175, 175}};
4965 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4966 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4967
chaviw9eaa22c2020-07-01 16:21:27 -07004968 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004969
chaviw9eaa22c2020-07-01 16:21:27 -07004970 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004971 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004972 expectedPoints.pop_back();
4973
4974 // Touch Window 2
4975 mWindow2->setWindowTransform(0, -1, 1, 0);
4976 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004977 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004978
4979 // Move both windows
4980 touchedPoints = {{20, 20}, {175, 175}};
4981 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4982 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4983
4984 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004985}
4986
4987TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4988 mWindow1->setWindowScale(0.5f, 0.5f);
4989
4990 // Touch Window 1
4991 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4992 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004993 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004994
4995 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004996 touchedPoints.push_back(PointF{150, 150});
4997 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004998
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004999 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005000
5001 // Move both windows
5002 touchedPoints = {{20, 20}, {175, 175}};
5003 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5004 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5005
chaviw9eaa22c2020-07-01 16:21:27 -07005006 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005007}
5008
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005009class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
5010 virtual void SetUp() override {
5011 InputDispatcherTest::SetUp();
5012
Chris Yea209fde2020-07-22 13:54:51 -07005013 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005014 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005015 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
5016 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005017 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005018 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07005019 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005020
5021 // Set focused application.
5022 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
5023
5024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005025 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005026 mWindow->consumeFocusEvent(true);
5027 }
5028
5029 virtual void TearDown() override {
5030 InputDispatcherTest::TearDown();
5031 mWindow.clear();
5032 }
5033
5034protected:
Chris Yea209fde2020-07-22 13:54:51 -07005035 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005036 sp<FakeWindowHandle> mWindow;
5037 static constexpr PointF WINDOW_LOCATION = {20, 20};
5038
5039 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005041 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5042 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005044 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5045 WINDOW_LOCATION));
5046 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005047
5048 sp<FakeWindowHandle> addSpyWindow() {
5049 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005050 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005051 spy->setTrustedOverlay(true);
5052 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005053 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005054 spy->setDispatchingTimeout(30ms);
5055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
5056 return spy;
5057 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005058};
5059
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005060// Send a tap and respond, which should not cause an ANR.
5061TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
5062 tapOnWindow();
5063 mWindow->consumeMotionDown();
5064 mWindow->consumeMotionUp();
5065 ASSERT_TRUE(mDispatcher->waitForIdle());
5066 mFakePolicy->assertNotifyAnrWasNotCalled();
5067}
5068
5069// Send a regular key and respond, which should not cause an ANR.
5070TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005072 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5073 ASSERT_TRUE(mDispatcher->waitForIdle());
5074 mFakePolicy->assertNotifyAnrWasNotCalled();
5075}
5076
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005077TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
5078 mWindow->setFocusable(false);
5079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5080 mWindow->consumeFocusEvent(false);
5081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005083 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005084 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5085 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005087 // Key will not go to window because we have no focused window.
5088 // The 'no focused window' ANR timer should start instead.
5089
5090 // Now, the focused application goes away.
5091 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
5092 // The key should get dropped and there should be no ANR.
5093
5094 ASSERT_TRUE(mDispatcher->waitForIdle());
5095 mFakePolicy->assertNotifyAnrWasNotCalled();
5096}
5097
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005098// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
5100// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005101TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005103 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5104 WINDOW_LOCATION));
5105
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005106 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
5107 ASSERT_TRUE(sequenceNum);
5108 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005109 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005111 mWindow->finishEvent(*sequenceNum);
5112 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5113 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005115 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005116}
5117
5118// Send a key to the app and have the app not respond right away.
5119TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
5120 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005122 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
5123 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005124 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005125 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005126 ASSERT_TRUE(mDispatcher->waitForIdle());
5127}
5128
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005129// We have a focused application, but no focused window
5130TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005131 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5133 mWindow->consumeFocusEvent(false);
5134
5135 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005137 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5138 WINDOW_LOCATION));
5139 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
5140 mDispatcher->waitForIdle();
5141 mFakePolicy->assertNotifyAnrWasNotCalled();
5142
5143 // Once a focused event arrives, we get an ANR for this application
5144 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5145 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005146 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005147 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005148 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005149 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005150 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07005151 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152 ASSERT_TRUE(mDispatcher->waitForIdle());
5153}
5154
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005155/**
5156 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
5157 * there will not be an ANR.
5158 */
5159TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
5160 mWindow->setFocusable(false);
5161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5162 mWindow->consumeFocusEvent(false);
5163
5164 KeyEvent event;
5165 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
5166 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
5167
5168 // Define a valid key down event that is stale (too old).
5169 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
5170 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
5171 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
5172
5173 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
5174
5175 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00005176 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005177 InputEventInjectionSync::WAIT_FOR_RESULT,
5178 INJECT_EVENT_TIMEOUT, policyFlags);
5179 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
5180 << "Injection should fail because the event is stale";
5181
5182 ASSERT_TRUE(mDispatcher->waitForIdle());
5183 mFakePolicy->assertNotifyAnrWasNotCalled();
5184 mWindow->assertNoEvents();
5185}
5186
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005187// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005188// Make sure that we don't notify policy twice about the same ANR.
5189TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
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);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005193
5194 // Once a focused event arrives, we get an ANR for this application
5195 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5196 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005197 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005198 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005199 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005200 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005201 const std::chrono::duration appTimeout =
5202 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5203 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005204
Vishnu Naire4df8752022-09-08 09:17:55 -07005205 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005206 // ANR should not be raised again. It is up to policy to do that if it desires.
5207 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005208
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005209 // If we now get a focused window, the ANR should stop, but the policy handles that via
5210 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 ASSERT_TRUE(mDispatcher->waitForIdle());
5212}
5213
5214// We have a focused application, but no focused window
5215TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005216 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5218 mWindow->consumeFocusEvent(false);
5219
5220 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005221 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005223 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5224 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225
Vishnu Naire4df8752022-09-08 09:17:55 -07005226 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5227 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005228
5229 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005230 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231 ASSERT_TRUE(mDispatcher->waitForIdle());
5232 mWindow->assertNoEvents();
5233}
5234
5235/**
5236 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5237 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5238 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5239 * the ANR mechanism should still work.
5240 *
5241 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5242 * DOWN event, while not responding on the second one.
5243 */
5244TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5245 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5246 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5247 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5248 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5249 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005250 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005251
5252 // Now send ACTION_UP, with identical timestamp
5253 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5254 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5255 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5256 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005257 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005258
5259 // We have now sent down and up. Let's consume first event and then ANR on the second.
5260 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5261 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005262 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005263}
5264
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005265// A spy window can receive an ANR
5266TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5267 sp<FakeWindowHandle> spy = addSpyWindow();
5268
5269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5271 WINDOW_LOCATION));
5272 mWindow->consumeMotionDown();
5273
5274 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5275 ASSERT_TRUE(sequenceNum);
5276 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005277 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005278
5279 spy->finishEvent(*sequenceNum);
5280 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
5281 0 /*flags*/);
5282 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005283 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005284}
5285
5286// If an app is not responding to a key 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, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5289 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5292 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005293 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005295
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->consumeKeyUp(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();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005310}
5311
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005312// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005313// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005314TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5315 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005316
5317 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005318 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5319 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320
5321 mWindow->consumeMotionDown();
5322 // Stuck on the ACTION_UP
5323 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005324 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005325
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005326 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005327 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005328 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5329 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005330
5331 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5332 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005333 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005334 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005335 spy->assertNoEvents();
5336}
5337
5338TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5339 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5340
5341 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5342
5343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5344 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5345 WINDOW_LOCATION));
5346
5347 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5348 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5349 ASSERT_TRUE(consumeSeq);
5350
Prabir Pradhanedd96402022-02-15 01:46:16 -08005351 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005352
5353 monitor.finishEvent(*consumeSeq);
5354 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5355
5356 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005357 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358}
5359
5360// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5361// process events, you don't get an anr. When the window later becomes unresponsive again, you
5362// get an ANR again.
5363// 1. tap -> block on ACTION_UP -> receive ANR
5364// 2. consume all pending events (= queue becomes healthy again)
5365// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5366TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5367 tapOnWindow();
5368
5369 mWindow->consumeMotionDown();
5370 // Block on ACTION_UP
5371 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005372 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005373 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5374 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005375 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376 mWindow->assertNoEvents();
5377
5378 tapOnWindow();
5379 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005380 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005381 mWindow->consumeMotionUp();
5382
5383 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005384 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005385 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005386 mWindow->assertNoEvents();
5387}
5388
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005389// If a connection remains unresponsive for a while, make sure policy is only notified once about
5390// it.
5391TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5394 WINDOW_LOCATION));
5395
5396 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005397 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005398 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005399 // 'notifyConnectionUnresponsive' should only be called once per connection
5400 mFakePolicy->assertNotifyAnrWasNotCalled();
5401 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005402 mWindow->consumeMotionDown();
5403 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5404 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5405 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005406 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005407 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005408 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005409}
5410
5411/**
5412 * If a window is processing a motion event, and then a key event comes in, the key event should
5413 * not to to the focused window until the motion is processed.
5414 *
5415 * Warning!!!
5416 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5417 * and the injection timeout that we specify when injecting the key.
5418 * We must have the injection timeout (10ms) be smaller than
5419 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5420 *
5421 * If that value changes, this test should also change.
5422 */
5423TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5424 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5426
5427 tapOnWindow();
5428 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5429 ASSERT_TRUE(downSequenceNum);
5430 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5431 ASSERT_TRUE(upSequenceNum);
5432 // Don't finish the events yet, and send a key
5433 // Injection will "succeed" because we will eventually give up and send the key to the focused
5434 // window even if motions are still being processed. But because the injection timeout is short,
5435 // we will receive INJECTION_TIMED_OUT as the result.
5436
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005437 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005438 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005439 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5440 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005441 // Key will not be sent to the window, yet, because the window is still processing events
5442 // and the key remains pending, waiting for the touch events to be processed
5443 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5444 ASSERT_FALSE(keySequenceNum);
5445
5446 std::this_thread::sleep_for(500ms);
5447 // if we wait long enough though, dispatcher will give up, and still send the key
5448 // to the focused window, even though we have not yet finished the motion event
5449 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5450 mWindow->finishEvent(*downSequenceNum);
5451 mWindow->finishEvent(*upSequenceNum);
5452}
5453
5454/**
5455 * If a window is processing a motion event, and then a key event comes in, the key event should
5456 * not go to the focused window until the motion is processed.
5457 * If then a new motion comes in, then the pending key event should be going to the currently
5458 * focused window right away.
5459 */
5460TEST_F(InputDispatcherSingleWindowAnr,
5461 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5462 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5464
5465 tapOnWindow();
5466 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5467 ASSERT_TRUE(downSequenceNum);
5468 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5469 ASSERT_TRUE(upSequenceNum);
5470 // Don't finish the events yet, and send a key
5471 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005473 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005474 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005475 // At this point, key is still pending, and should not be sent to the application yet.
5476 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5477 ASSERT_FALSE(keySequenceNum);
5478
5479 // Now tap down again. It should cause the pending key to go to the focused window right away.
5480 tapOnWindow();
5481 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5482 // the other events yet. We can finish events in any order.
5483 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5484 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5485 mWindow->consumeMotionDown();
5486 mWindow->consumeMotionUp();
5487 mWindow->assertNoEvents();
5488}
5489
5490class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5491 virtual void SetUp() override {
5492 InputDispatcherTest::SetUp();
5493
Chris Yea209fde2020-07-22 13:54:51 -07005494 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005495 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005496 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5497 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005498 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005499 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005500 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005502 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5503 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005504 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005505 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005506
5507 // Set focused application.
5508 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005509 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005510
5511 // Expect one focus window exist in display.
5512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005513 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005514 mFocusedWindow->consumeFocusEvent(true);
5515 }
5516
5517 virtual void TearDown() override {
5518 InputDispatcherTest::TearDown();
5519
5520 mUnfocusedWindow.clear();
5521 mFocusedWindow.clear();
5522 }
5523
5524protected:
Chris Yea209fde2020-07-22 13:54:51 -07005525 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005526 sp<FakeWindowHandle> mUnfocusedWindow;
5527 sp<FakeWindowHandle> mFocusedWindow;
5528 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5529 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5530 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5531
5532 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5533
5534 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5535
5536private:
5537 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5540 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005542 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5543 location));
5544 }
5545};
5546
5547// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5548// should be ANR'd first.
5549TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5552 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005553 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005554 mFocusedWindow->consumeMotionDown();
5555 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5556 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5557 // We consumed all events, so no ANR
5558 ASSERT_TRUE(mDispatcher->waitForIdle());
5559 mFakePolicy->assertNotifyAnrWasNotCalled();
5560
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5563 FOCUSED_WINDOW_LOCATION));
5564 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5565 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566
5567 const std::chrono::duration timeout =
5568 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005569 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005570 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5571 // sequence to make it consistent
5572 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005573 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005574 mFocusedWindow->consumeMotionDown();
5575 // This cancel is generated because the connection was unresponsive
5576 mFocusedWindow->consumeMotionCancel();
5577 mFocusedWindow->assertNoEvents();
5578 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005579 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005580 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5581 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005582 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005583}
5584
5585// If we have 2 windows with identical timeouts that are both unresponsive,
5586// it doesn't matter which order they should have ANR.
5587// But we should receive ANR for both.
5588TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5589 // Set the timeout for unfocused window to match the focused window
5590 mUnfocusedWindow->setDispatchingTimeout(10ms);
5591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5592
5593 tapOnFocusedWindow();
5594 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005595 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5596 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5597 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005598
5599 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005600 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5601 mFocusedWindow->getToken() == anrConnectionToken2);
5602 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5603 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005604
5605 ASSERT_TRUE(mDispatcher->waitForIdle());
5606 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005607
5608 mFocusedWindow->consumeMotionDown();
5609 mFocusedWindow->consumeMotionUp();
5610 mUnfocusedWindow->consumeMotionOutside();
5611
Prabir Pradhanedd96402022-02-15 01:46:16 -08005612 sp<IBinder> responsiveToken1, responsiveToken2;
5613 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5614 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005615
5616 // Both applications should be marked as responsive, in any order
5617 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5618 mFocusedWindow->getToken() == responsiveToken2);
5619 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5620 mUnfocusedWindow->getToken() == responsiveToken2);
5621 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622}
5623
5624// If a window is already not responding, the second tap on the same window should be ignored.
5625// We should also log an error to account for the dropped event (not tested here).
5626// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5627TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5628 tapOnFocusedWindow();
5629 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5630 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5631 // Receive the events, but don't respond
5632 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5633 ASSERT_TRUE(downEventSequenceNum);
5634 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5635 ASSERT_TRUE(upEventSequenceNum);
5636 const std::chrono::duration timeout =
5637 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005638 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005639
5640 // Tap once again
5641 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005642 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005643 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5644 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005645 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005646 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5647 FOCUSED_WINDOW_LOCATION));
5648 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5649 // valid touch target
5650 mUnfocusedWindow->assertNoEvents();
5651
5652 // Consume the first tap
5653 mFocusedWindow->finishEvent(*downEventSequenceNum);
5654 mFocusedWindow->finishEvent(*upEventSequenceNum);
5655 ASSERT_TRUE(mDispatcher->waitForIdle());
5656 // The second tap did not go to the focused window
5657 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005658 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005659 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5660 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005661 mFakePolicy->assertNotifyAnrWasNotCalled();
5662}
5663
5664// If you tap outside of all windows, there will not be ANR
5665TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5668 LOCATION_OUTSIDE_ALL_WINDOWS));
5669 ASSERT_TRUE(mDispatcher->waitForIdle());
5670 mFakePolicy->assertNotifyAnrWasNotCalled();
5671}
5672
5673// Since the focused window is paused, tapping on it should not produce any events
5674TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5675 mFocusedWindow->setPaused(true);
5676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5677
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005678 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005679 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5680 FOCUSED_WINDOW_LOCATION));
5681
5682 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5683 ASSERT_TRUE(mDispatcher->waitForIdle());
5684 // Should not ANR because the window is paused, and touches shouldn't go to it
5685 mFakePolicy->assertNotifyAnrWasNotCalled();
5686
5687 mFocusedWindow->assertNoEvents();
5688 mUnfocusedWindow->assertNoEvents();
5689}
5690
5691/**
5692 * If a window is processing a motion event, and then a key event comes in, the key event should
5693 * not to to the focused window until the motion is processed.
5694 * If a different window becomes focused at this time, the key should go to that window instead.
5695 *
5696 * Warning!!!
5697 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5698 * and the injection timeout that we specify when injecting the key.
5699 * We must have the injection timeout (10ms) be smaller than
5700 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5701 *
5702 * If that value changes, this test should also change.
5703 */
5704TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5705 // Set a long ANR timeout to prevent it from triggering
5706 mFocusedWindow->setDispatchingTimeout(2s);
5707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5708
5709 tapOnUnfocusedWindow();
5710 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5711 ASSERT_TRUE(downSequenceNum);
5712 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5713 ASSERT_TRUE(upSequenceNum);
5714 // Don't finish the events yet, and send a key
5715 // Injection will succeed because we will eventually give up and send the key to the focused
5716 // window even if motions are still being processed.
5717
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005718 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005719 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005720 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 // Key will not be sent to the window, yet, because the window is still processing events
5723 // and the key remains pending, waiting for the touch events to be processed
5724 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5725 ASSERT_FALSE(keySequenceNum);
5726
5727 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005728 mFocusedWindow->setFocusable(false);
5729 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005731 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005732
5733 // Focus events should precede the key events
5734 mUnfocusedWindow->consumeFocusEvent(true);
5735 mFocusedWindow->consumeFocusEvent(false);
5736
5737 // Finish the tap events, which should unblock dispatcher
5738 mUnfocusedWindow->finishEvent(*downSequenceNum);
5739 mUnfocusedWindow->finishEvent(*upSequenceNum);
5740
5741 // Now that all queues are cleared and no backlog in the connections, the key event
5742 // can finally go to the newly focused "mUnfocusedWindow".
5743 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5744 mFocusedWindow->assertNoEvents();
5745 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005746 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005747}
5748
5749// When the touch stream is split across 2 windows, and one of them does not respond,
5750// then ANR should be raised and the touch should be canceled for the unresponsive window.
5751// The other window should not be affected by that.
5752TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5753 // Touch Window 1
5754 NotifyMotionArgs motionArgs =
5755 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5756 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5757 mDispatcher->notifyMotion(&motionArgs);
5758 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5759 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5760
5761 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005762 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5763 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005764 mDispatcher->notifyMotion(&motionArgs);
5765
5766 const std::chrono::duration timeout =
5767 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005768 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005769
5770 mUnfocusedWindow->consumeMotionDown();
5771 mFocusedWindow->consumeMotionDown();
5772 // Focused window may or may not receive ACTION_MOVE
5773 // But it should definitely receive ACTION_CANCEL due to the ANR
5774 InputEvent* event;
5775 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5776 ASSERT_TRUE(moveOrCancelSequenceNum);
5777 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5778 ASSERT_NE(nullptr, event);
5779 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5780 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5781 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5782 mFocusedWindow->consumeMotionCancel();
5783 } else {
5784 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5785 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005787 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5788 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005789
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005790 mUnfocusedWindow->assertNoEvents();
5791 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005792 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005793}
5794
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005795/**
5796 * If we have no focused window, and a key comes in, we start the ANR timer.
5797 * The focused application should add a focused window before the timer runs out to prevent ANR.
5798 *
5799 * If the user touches another application during this time, the key should be dropped.
5800 * Next, if a new focused window comes in, without toggling the focused application,
5801 * then no ANR should occur.
5802 *
5803 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5804 * but in some cases the policy may not update the focused application.
5805 */
5806TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5807 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5808 std::make_shared<FakeApplicationHandle>();
5809 focusedApplication->setDispatchingTimeout(60ms);
5810 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5811 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5812 mFocusedWindow->setFocusable(false);
5813
5814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5815 mFocusedWindow->consumeFocusEvent(false);
5816
5817 // Send a key. The ANR timer should start because there is no focused window.
5818 // 'focusedApplication' will get blamed if this timer completes.
5819 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005820 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005821 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005822 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5823 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005825
5826 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5827 // then the injected touches won't cause the focused event to get dropped.
5828 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5829 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5830 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5831 // For this test, it means that the key would get delivered to the window once it becomes
5832 // focused.
5833 std::this_thread::sleep_for(10ms);
5834
5835 // Touch unfocused window. This should force the pending key to get dropped.
5836 NotifyMotionArgs motionArgs =
5837 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5838 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5839 mDispatcher->notifyMotion(&motionArgs);
5840
5841 // We do not consume the motion right away, because that would require dispatcher to first
5842 // process (== drop) the key event, and by that time, ANR will be raised.
5843 // Set the focused window first.
5844 mFocusedWindow->setFocusable(true);
5845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5846 setFocusedWindow(mFocusedWindow);
5847 mFocusedWindow->consumeFocusEvent(true);
5848 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5849 // to another application. This could be a bug / behaviour in the policy.
5850
5851 mUnfocusedWindow->consumeMotionDown();
5852
5853 ASSERT_TRUE(mDispatcher->waitForIdle());
5854 // Should not ANR because we actually have a focused window. It was just added too slowly.
5855 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5856}
5857
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005858// These tests ensure we cannot send touch events to a window that's positioned behind a window
5859// that has feature NO_INPUT_CHANNEL.
5860// Layout:
5861// Top (closest to user)
5862// mNoInputWindow (above all windows)
5863// mBottomWindow
5864// Bottom (furthest from user)
5865class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5866 virtual void SetUp() override {
5867 InputDispatcherTest::SetUp();
5868
5869 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005870 mNoInputWindow =
5871 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5872 "Window without input channel", ADISPLAY_ID_DEFAULT,
5873 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005874 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005875 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5876 // It's perfectly valid for this window to not have an associated input channel
5877
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005878 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5879 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005880 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5881
5882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5883 }
5884
5885protected:
5886 std::shared_ptr<FakeApplicationHandle> mApplication;
5887 sp<FakeWindowHandle> mNoInputWindow;
5888 sp<FakeWindowHandle> mBottomWindow;
5889};
5890
5891TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5892 PointF touchedPoint = {10, 10};
5893
5894 NotifyMotionArgs motionArgs =
5895 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5896 ADISPLAY_ID_DEFAULT, {touchedPoint});
5897 mDispatcher->notifyMotion(&motionArgs);
5898
5899 mNoInputWindow->assertNoEvents();
5900 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5901 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5902 // and therefore should prevent mBottomWindow from receiving touches
5903 mBottomWindow->assertNoEvents();
5904}
5905
5906/**
5907 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5908 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5909 */
5910TEST_F(InputDispatcherMultiWindowOcclusionTests,
5911 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005912 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5913 "Window with input channel and NO_INPUT_CHANNEL",
5914 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005915
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005916 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005917 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5919
5920 PointF touchedPoint = {10, 10};
5921
5922 NotifyMotionArgs motionArgs =
5923 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5924 ADISPLAY_ID_DEFAULT, {touchedPoint});
5925 mDispatcher->notifyMotion(&motionArgs);
5926
5927 mNoInputWindow->assertNoEvents();
5928 mBottomWindow->assertNoEvents();
5929}
5930
Vishnu Nair958da932020-08-21 17:12:37 -07005931class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5932protected:
5933 std::shared_ptr<FakeApplicationHandle> mApp;
5934 sp<FakeWindowHandle> mWindow;
5935 sp<FakeWindowHandle> mMirror;
5936
5937 virtual void SetUp() override {
5938 InputDispatcherTest::SetUp();
5939 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005940 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5941 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5942 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005943 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5944 mWindow->setFocusable(true);
5945 mMirror->setFocusable(true);
5946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5947 }
5948};
5949
5950TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5951 // Request focus on a mirrored window
5952 setFocusedWindow(mMirror);
5953
5954 // window gets focused
5955 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5957 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005958 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5959}
5960
5961// A focused & mirrored window remains focused only if the window and its mirror are both
5962// focusable.
5963TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5964 setFocusedWindow(mMirror);
5965
5966 // window gets focused
5967 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5969 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005970 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5972 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005973 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5974
5975 mMirror->setFocusable(false);
5976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5977
5978 // window loses focus since one of the windows associated with the token in not focusable
5979 mWindow->consumeFocusEvent(false);
5980
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005981 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5982 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005983 mWindow->assertNoEvents();
5984}
5985
5986// A focused & mirrored window remains focused until the window and its mirror both become
5987// invisible.
5988TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5989 setFocusedWindow(mMirror);
5990
5991 // window gets focused
5992 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5994 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005995 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5997 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005998 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5999
6000 mMirror->setVisible(false);
6001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6004 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006005 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6007 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006008 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6009
6010 mWindow->setVisible(false);
6011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6012
6013 // window loses focus only after all windows associated with the token become invisible.
6014 mWindow->consumeFocusEvent(false);
6015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006016 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6017 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006018 mWindow->assertNoEvents();
6019}
6020
6021// A focused & mirrored window remains focused until both windows are removed.
6022TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
6023 setFocusedWindow(mMirror);
6024
6025 // window gets focused
6026 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6028 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006029 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6031 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006032 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6033
6034 // single window is removed but the window token remains focused
6035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
6036
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006037 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6038 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006039 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6041 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006042 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6043
6044 // Both windows are removed
6045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
6046 mWindow->consumeFocusEvent(false);
6047
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006048 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6049 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006050 mWindow->assertNoEvents();
6051}
6052
6053// Focus request can be pending until one window becomes visible.
6054TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
6055 // Request focus on an invisible mirror.
6056 mWindow->setVisible(false);
6057 mMirror->setVisible(false);
6058 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6059 setFocusedWindow(mMirror);
6060
6061 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07006063 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006064 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07006065
6066 mMirror->setVisible(true);
6067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6068
6069 // window gets focused
6070 mWindow->consumeFocusEvent(true);
6071 // window gets the pending key event
6072 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6073}
Prabir Pradhan99987712020-11-10 18:43:05 -08006074
6075class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
6076protected:
6077 std::shared_ptr<FakeApplicationHandle> mApp;
6078 sp<FakeWindowHandle> mWindow;
6079 sp<FakeWindowHandle> mSecondWindow;
6080
6081 void SetUp() override {
6082 InputDispatcherTest::SetUp();
6083 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006084 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006085 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006086 mSecondWindow =
6087 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006088 mSecondWindow->setFocusable(true);
6089
6090 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6092
6093 setFocusedWindow(mWindow);
6094 mWindow->consumeFocusEvent(true);
6095 }
6096
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006097 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
6098 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006099 mDispatcher->notifyPointerCaptureChanged(&args);
6100 }
6101
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006102 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
6103 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006104 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006105 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
6106 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006107 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006108 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08006109 }
6110};
6111
6112TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
6113 // Ensure that capture cannot be obtained for unfocused windows.
6114 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
6115 mFakePolicy->assertSetPointerCaptureNotCalled();
6116 mSecondWindow->assertNoEvents();
6117
6118 // Ensure that capture can be enabled from the focus window.
6119 requestAndVerifyPointerCapture(mWindow, true);
6120
6121 // Ensure that capture cannot be disabled from a window that does not have capture.
6122 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
6123 mFakePolicy->assertSetPointerCaptureNotCalled();
6124
6125 // Ensure that capture can be disabled from the window with capture.
6126 requestAndVerifyPointerCapture(mWindow, false);
6127}
6128
6129TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006130 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006131
6132 setFocusedWindow(mSecondWindow);
6133
6134 // Ensure that the capture disabled event was sent first.
6135 mWindow->consumeCaptureEvent(false);
6136 mWindow->consumeFocusEvent(false);
6137 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006138 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006139
6140 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006141 notifyPointerCaptureChanged({});
6142 notifyPointerCaptureChanged(request);
6143 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08006144 mWindow->assertNoEvents();
6145 mSecondWindow->assertNoEvents();
6146 mFakePolicy->assertSetPointerCaptureNotCalled();
6147}
6148
6149TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006150 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006151
6152 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006153 notifyPointerCaptureChanged({});
6154 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006155
6156 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006157 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006158 mWindow->consumeCaptureEvent(false);
6159 mWindow->assertNoEvents();
6160}
6161
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006162TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
6163 requestAndVerifyPointerCapture(mWindow, true);
6164
6165 // The first window loses focus.
6166 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006167 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006168 mWindow->consumeCaptureEvent(false);
6169
6170 // Request Pointer Capture from the second window before the notification from InputReader
6171 // arrives.
6172 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006173 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006174
6175 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006176 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006177
6178 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006179 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006180
6181 mSecondWindow->consumeFocusEvent(true);
6182 mSecondWindow->consumeCaptureEvent(true);
6183}
6184
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006185TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
6186 // App repeatedly enables and disables capture.
6187 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6188 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6189 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6190 mFakePolicy->assertSetPointerCaptureCalled(false);
6191 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6192 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6193
6194 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6195 // first request is now stale, this should do nothing.
6196 notifyPointerCaptureChanged(firstRequest);
6197 mWindow->assertNoEvents();
6198
6199 // InputReader notifies that the second request was enabled.
6200 notifyPointerCaptureChanged(secondRequest);
6201 mWindow->consumeCaptureEvent(true);
6202}
6203
Prabir Pradhan7092e262022-05-03 16:51:09 +00006204TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6205 requestAndVerifyPointerCapture(mWindow, true);
6206
6207 // App toggles pointer capture off and on.
6208 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6209 mFakePolicy->assertSetPointerCaptureCalled(false);
6210
6211 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6212 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6213
6214 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6215 // preceding "disable" request.
6216 notifyPointerCaptureChanged(enableRequest);
6217
6218 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6219 // any notifications.
6220 mWindow->assertNoEvents();
6221}
6222
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006223class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6224protected:
6225 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006226
6227 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6228 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6229
6230 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6231 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6232
6233 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6234 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6235 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6236 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6237 MAXIMUM_OBSCURING_OPACITY);
6238
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006239 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006240 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006241 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006242
6243 sp<FakeWindowHandle> mTouchWindow;
6244
6245 virtual void SetUp() override {
6246 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006247 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006248 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6249 }
6250
6251 virtual void TearDown() override {
6252 InputDispatcherTest::TearDown();
6253 mTouchWindow.clear();
6254 }
6255
chaviw3277faf2021-05-19 16:45:23 -05006256 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6257 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006258 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006259 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006260 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006261 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006262 return window;
6263 }
6264
6265 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6266 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6267 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006268 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006269 // Generate an arbitrary PID based on the UID
6270 window->setOwnerInfo(1777 + (uid % 10000), uid);
6271 return window;
6272 }
6273
6274 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6275 NotifyMotionArgs args =
6276 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6277 ADISPLAY_ID_DEFAULT, points);
6278 mDispatcher->notifyMotion(&args);
6279 }
6280};
6281
6282TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006283 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006284 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006285 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006286
6287 touch();
6288
6289 mTouchWindow->assertNoEvents();
6290}
6291
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006292TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006293 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6294 const sp<FakeWindowHandle>& w =
6295 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6297
6298 touch();
6299
6300 mTouchWindow->assertNoEvents();
6301}
6302
6303TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006304 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6305 const sp<FakeWindowHandle>& w =
6306 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6308
6309 touch();
6310
6311 w->assertNoEvents();
6312}
6313
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006314TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006315 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006317
6318 touch();
6319
6320 mTouchWindow->consumeAnyMotionDown();
6321}
6322
6323TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006324 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006325 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006326 w->setFrame(Rect(0, 0, 50, 50));
6327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006328
6329 touch({PointF{100, 100}});
6330
6331 mTouchWindow->consumeAnyMotionDown();
6332}
6333
6334TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006335 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006336 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6338
6339 touch();
6340
6341 mTouchWindow->consumeAnyMotionDown();
6342}
6343
6344TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6345 const sp<FakeWindowHandle>& w =
6346 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006348
6349 touch();
6350
6351 mTouchWindow->consumeAnyMotionDown();
6352}
6353
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006354TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6355 const sp<FakeWindowHandle>& w =
6356 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6358
6359 touch();
6360
6361 w->assertNoEvents();
6362}
6363
6364/**
6365 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6366 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6367 * window, the occluding window will still receive ACTION_OUTSIDE event.
6368 */
6369TEST_F(InputDispatcherUntrustedTouchesTest,
6370 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6371 const sp<FakeWindowHandle>& w =
6372 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006373 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6375
6376 touch();
6377
6378 w->consumeMotionOutside();
6379}
6380
6381TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6382 const sp<FakeWindowHandle>& w =
6383 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006384 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6386
6387 touch();
6388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006389 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006390}
6391
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006392TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006393 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006394 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6395 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6397
6398 touch();
6399
6400 mTouchWindow->consumeAnyMotionDown();
6401}
6402
6403TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6404 const sp<FakeWindowHandle>& w =
6405 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6406 MAXIMUM_OBSCURING_OPACITY);
6407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006408
6409 touch();
6410
6411 mTouchWindow->consumeAnyMotionDown();
6412}
6413
6414TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006415 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006416 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6417 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6419
6420 touch();
6421
6422 mTouchWindow->assertNoEvents();
6423}
6424
6425TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6426 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6427 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006428 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6429 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006430 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006431 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6432 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6434
6435 touch();
6436
6437 mTouchWindow->assertNoEvents();
6438}
6439
6440TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6441 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6442 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006443 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6444 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006445 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006446 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6447 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006448 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6449
6450 touch();
6451
6452 mTouchWindow->consumeAnyMotionDown();
6453}
6454
6455TEST_F(InputDispatcherUntrustedTouchesTest,
6456 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6457 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006458 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6459 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006460 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006461 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6462 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6464
6465 touch();
6466
6467 mTouchWindow->consumeAnyMotionDown();
6468}
6469
6470TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6471 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006472 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6473 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006474 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006475 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6476 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006478
6479 touch();
6480
6481 mTouchWindow->assertNoEvents();
6482}
6483
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006484TEST_F(InputDispatcherUntrustedTouchesTest,
6485 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6486 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006487 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6488 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006489 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006490 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6491 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6493
6494 touch();
6495
6496 mTouchWindow->assertNoEvents();
6497}
6498
6499TEST_F(InputDispatcherUntrustedTouchesTest,
6500 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6501 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006502 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6503 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006504 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006505 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6506 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6508
6509 touch();
6510
6511 mTouchWindow->consumeAnyMotionDown();
6512}
6513
6514TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6515 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006516 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6517 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6519
6520 touch();
6521
6522 mTouchWindow->consumeAnyMotionDown();
6523}
6524
6525TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6526 const sp<FakeWindowHandle>& w =
6527 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6529
6530 touch();
6531
6532 mTouchWindow->consumeAnyMotionDown();
6533}
6534
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006535TEST_F(InputDispatcherUntrustedTouchesTest,
6536 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6537 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6538 const sp<FakeWindowHandle>& w =
6539 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6541
6542 touch();
6543
6544 mTouchWindow->assertNoEvents();
6545}
6546
6547TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6548 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6549 const sp<FakeWindowHandle>& w =
6550 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6552
6553 touch();
6554
6555 mTouchWindow->consumeAnyMotionDown();
6556}
6557
6558TEST_F(InputDispatcherUntrustedTouchesTest,
6559 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6560 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6561 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006562 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6563 OPACITY_ABOVE_THRESHOLD);
6564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6565
6566 touch();
6567
6568 mTouchWindow->consumeAnyMotionDown();
6569}
6570
6571TEST_F(InputDispatcherUntrustedTouchesTest,
6572 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6573 const sp<FakeWindowHandle>& w1 =
6574 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6575 OPACITY_BELOW_THRESHOLD);
6576 const sp<FakeWindowHandle>& w2 =
6577 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6578 OPACITY_BELOW_THRESHOLD);
6579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6580
6581 touch();
6582
6583 mTouchWindow->assertNoEvents();
6584}
6585
6586/**
6587 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6588 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6589 * (which alone would result in allowing touches) does not affect the blocking behavior.
6590 */
6591TEST_F(InputDispatcherUntrustedTouchesTest,
6592 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6593 const sp<FakeWindowHandle>& wB =
6594 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6595 OPACITY_BELOW_THRESHOLD);
6596 const sp<FakeWindowHandle>& wC =
6597 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6598 OPACITY_BELOW_THRESHOLD);
6599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6600
6601 touch();
6602
6603 mTouchWindow->assertNoEvents();
6604}
6605
6606/**
6607 * This test is testing that a window from a different UID but with same application token doesn't
6608 * block the touch. Apps can share the application token for close UI collaboration for example.
6609 */
6610TEST_F(InputDispatcherUntrustedTouchesTest,
6611 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6612 const sp<FakeWindowHandle>& w =
6613 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6614 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6616
6617 touch();
6618
6619 mTouchWindow->consumeAnyMotionDown();
6620}
6621
arthurhungb89ccb02020-12-30 16:19:01 +08006622class InputDispatcherDragTests : public InputDispatcherTest {
6623protected:
6624 std::shared_ptr<FakeApplicationHandle> mApp;
6625 sp<FakeWindowHandle> mWindow;
6626 sp<FakeWindowHandle> mSecondWindow;
6627 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006628 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006629 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6630 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006631
6632 void SetUp() override {
6633 InputDispatcherTest::SetUp();
6634 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006635 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006636 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006637
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006638 mSecondWindow =
6639 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006640 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006641
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006642 mSpyWindow =
6643 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006644 mSpyWindow->setSpy(true);
6645 mSpyWindow->setTrustedOverlay(true);
6646 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6647
arthurhungb89ccb02020-12-30 16:19:01 +08006648 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006650 }
6651
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006652 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6653 switch (fromSource) {
6654 case AINPUT_SOURCE_TOUCHSCREEN:
6655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6657 ADISPLAY_ID_DEFAULT, {50, 50}))
6658 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6659 break;
6660 case AINPUT_SOURCE_STYLUS:
6661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6662 injectMotionEvent(
6663 mDispatcher,
6664 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6665 AINPUT_SOURCE_STYLUS)
6666 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6667 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6668 .x(50)
6669 .y(50))
6670 .build()));
6671 break;
6672 case AINPUT_SOURCE_MOUSE:
6673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6674 injectMotionEvent(
6675 mDispatcher,
6676 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6677 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6678 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6679 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6680 .x(50)
6681 .y(50))
6682 .build()));
6683 break;
6684 default:
6685 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6686 }
arthurhungb89ccb02020-12-30 16:19:01 +08006687
6688 // Window should receive motion event.
6689 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006690 // Spy window should also receive motion event
6691 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006692 }
6693
6694 // Start performing drag, we will create a drag window and transfer touch to it.
6695 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6696 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006697 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006698 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006699 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006700 }
arthurhungb89ccb02020-12-30 16:19:01 +08006701
6702 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006703 mDragWindow =
6704 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006705 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006706 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006707 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006708
6709 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006710 bool transferred =
6711 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6712 true /* isDragDrop */);
6713 if (transferred) {
6714 mWindow->consumeMotionCancel();
6715 mDragWindow->consumeMotionDown();
6716 }
6717 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006718 }
6719};
6720
6721TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006722 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006723
6724 // Move on window.
6725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6726 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6727 ADISPLAY_ID_DEFAULT, {50, 50}))
6728 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6729 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6730 mWindow->consumeDragEvent(false, 50, 50);
6731 mSecondWindow->assertNoEvents();
6732
6733 // Move to another window.
6734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6735 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6736 ADISPLAY_ID_DEFAULT, {150, 50}))
6737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6738 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6739 mWindow->consumeDragEvent(true, 150, 50);
6740 mSecondWindow->consumeDragEvent(false, 50, 50);
6741
6742 // Move back to original window.
6743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6744 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6745 ADISPLAY_ID_DEFAULT, {50, 50}))
6746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6747 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6748 mWindow->consumeDragEvent(false, 50, 50);
6749 mSecondWindow->consumeDragEvent(true, -50, 50);
6750
6751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6752 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6754 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6755 mWindow->assertNoEvents();
6756 mSecondWindow->assertNoEvents();
6757}
6758
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006759TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006760 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006761
6762 // No cancel event after drag start
6763 mSpyWindow->assertNoEvents();
6764
6765 const MotionEvent secondFingerDownEvent =
6766 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6767 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6768 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6769 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6770 .build();
6771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6772 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6773 InputEventInjectionSync::WAIT_FOR_RESULT))
6774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6775
6776 // Receives cancel for first pointer after next pointer down
6777 mSpyWindow->consumeMotionCancel();
6778 mSpyWindow->consumeMotionDown();
6779
6780 mSpyWindow->assertNoEvents();
6781}
6782
arthurhungf452d0b2021-01-06 00:19:52 +08006783TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006784 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006785
6786 // Move on window.
6787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6788 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6789 ADISPLAY_ID_DEFAULT, {50, 50}))
6790 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6791 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6792 mWindow->consumeDragEvent(false, 50, 50);
6793 mSecondWindow->assertNoEvents();
6794
6795 // Move to another window.
6796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6797 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6798 ADISPLAY_ID_DEFAULT, {150, 50}))
6799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6800 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6801 mWindow->consumeDragEvent(true, 150, 50);
6802 mSecondWindow->consumeDragEvent(false, 50, 50);
6803
6804 // drop to another window.
6805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6806 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6807 {150, 50}))
6808 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6809 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6810 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6811 mWindow->assertNoEvents();
6812 mSecondWindow->assertNoEvents();
6813}
6814
arthurhung6d4bed92021-03-17 11:59:33 +08006815TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006816 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006817
6818 // Move on window and keep button pressed.
6819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6820 injectMotionEvent(mDispatcher,
6821 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6822 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6823 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6824 .x(50)
6825 .y(50))
6826 .build()))
6827 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6828 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6829 mWindow->consumeDragEvent(false, 50, 50);
6830 mSecondWindow->assertNoEvents();
6831
6832 // Move to another window and release button, expect to drop item.
6833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6834 injectMotionEvent(mDispatcher,
6835 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6836 .buttonState(0)
6837 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6838 .x(150)
6839 .y(50))
6840 .build()))
6841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6842 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6843 mWindow->assertNoEvents();
6844 mSecondWindow->assertNoEvents();
6845 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6846
6847 // nothing to the window.
6848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6849 injectMotionEvent(mDispatcher,
6850 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6851 .buttonState(0)
6852 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6853 .x(150)
6854 .y(50))
6855 .build()))
6856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6857 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6858 mWindow->assertNoEvents();
6859 mSecondWindow->assertNoEvents();
6860}
6861
Arthur Hung54745652022-04-20 07:17:41 +00006862TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006863 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006864
6865 // Set second window invisible.
6866 mSecondWindow->setVisible(false);
6867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6868
6869 // Move on window.
6870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6871 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6872 ADISPLAY_ID_DEFAULT, {50, 50}))
6873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6874 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6875 mWindow->consumeDragEvent(false, 50, 50);
6876 mSecondWindow->assertNoEvents();
6877
6878 // Move to another window.
6879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6880 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6881 ADISPLAY_ID_DEFAULT, {150, 50}))
6882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6883 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6884 mWindow->consumeDragEvent(true, 150, 50);
6885 mSecondWindow->assertNoEvents();
6886
6887 // drop to another window.
6888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6889 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6890 {150, 50}))
6891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6892 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6893 mFakePolicy->assertDropTargetEquals(nullptr);
6894 mWindow->assertNoEvents();
6895 mSecondWindow->assertNoEvents();
6896}
6897
Arthur Hung54745652022-04-20 07:17:41 +00006898TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006899 // Ensure window could track pointerIds if it didn't support split touch.
6900 mWindow->setPreventSplitting(true);
6901
Arthur Hung54745652022-04-20 07:17:41 +00006902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6903 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6904 {50, 50}))
6905 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6906 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6907
6908 const MotionEvent secondFingerDownEvent =
6909 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6910 .displayId(ADISPLAY_ID_DEFAULT)
6911 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6912 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6913 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6914 .build();
6915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6916 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6917 InputEventInjectionSync::WAIT_FOR_RESULT))
6918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6919 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6920
6921 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006922 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006923}
6924
6925TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6926 // First down on second window.
6927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6928 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6929 {150, 50}))
6930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6931
6932 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6933
6934 // Second down on first window.
6935 const MotionEvent secondFingerDownEvent =
6936 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6937 .displayId(ADISPLAY_ID_DEFAULT)
6938 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6939 .pointer(
6940 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6941 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6942 .build();
6943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6944 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6945 InputEventInjectionSync::WAIT_FOR_RESULT))
6946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6947 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6948
6949 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006950 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006951
6952 // Move on window.
6953 const MotionEvent secondFingerMoveEvent =
6954 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6955 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6956 .pointer(
6957 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6958 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6959 .build();
6960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6961 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6962 InputEventInjectionSync::WAIT_FOR_RESULT));
6963 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6964 mWindow->consumeDragEvent(false, 50, 50);
6965 mSecondWindow->consumeMotionMove();
6966
6967 // Release the drag pointer should perform drop.
6968 const MotionEvent secondFingerUpEvent =
6969 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6970 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6971 .pointer(
6972 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6973 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6974 .build();
6975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6976 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6977 InputEventInjectionSync::WAIT_FOR_RESULT));
6978 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6979 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6980 mWindow->assertNoEvents();
6981 mSecondWindow->consumeMotionMove();
6982}
6983
Arthur Hung3915c1f2022-05-31 07:17:17 +00006984TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006985 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006986
6987 // Update window of second display.
6988 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006989 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006990 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6991
6992 // Let second display has a touch state.
6993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6994 injectMotionEvent(mDispatcher,
6995 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6996 AINPUT_SOURCE_TOUCHSCREEN)
6997 .displayId(SECOND_DISPLAY_ID)
6998 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6999 .x(100)
7000 .y(100))
7001 .build()));
7002 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
7003 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
7004 // Update window again.
7005 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7006
7007 // Move on window.
7008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7009 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7010 ADISPLAY_ID_DEFAULT, {50, 50}))
7011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7012 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7013 mWindow->consumeDragEvent(false, 50, 50);
7014 mSecondWindow->assertNoEvents();
7015
7016 // Move to another window.
7017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7018 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7019 ADISPLAY_ID_DEFAULT, {150, 50}))
7020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7021 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7022 mWindow->consumeDragEvent(true, 150, 50);
7023 mSecondWindow->consumeDragEvent(false, 50, 50);
7024
7025 // drop to another window.
7026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7027 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7028 {150, 50}))
7029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7030 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7031 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7032 mWindow->assertNoEvents();
7033 mSecondWindow->assertNoEvents();
7034}
7035
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007036TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
7037 startDrag(true, AINPUT_SOURCE_MOUSE);
7038 // Move on window.
7039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7040 injectMotionEvent(mDispatcher,
7041 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7042 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7043 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7044 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7045 .x(50)
7046 .y(50))
7047 .build()))
7048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7049 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7050 mWindow->consumeDragEvent(false, 50, 50);
7051 mSecondWindow->assertNoEvents();
7052
7053 // Move to another window.
7054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7055 injectMotionEvent(mDispatcher,
7056 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7057 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7058 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7059 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7060 .x(150)
7061 .y(50))
7062 .build()))
7063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7064 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7065 mWindow->consumeDragEvent(true, 150, 50);
7066 mSecondWindow->consumeDragEvent(false, 50, 50);
7067
7068 // drop to another window.
7069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7070 injectMotionEvent(mDispatcher,
7071 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
7072 .buttonState(0)
7073 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7074 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7075 .x(150)
7076 .y(50))
7077 .build()))
7078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7079 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7080 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7081 mWindow->assertNoEvents();
7082 mSecondWindow->assertNoEvents();
7083}
7084
Vishnu Nair062a8672021-09-03 16:07:44 -07007085class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
7086
7087TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
7088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007089 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7090 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007091 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007092 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7093 window->setFocusable(true);
7094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7095 setFocusedWindow(window);
7096 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7097
7098 // With the flag set, window should not get any input
7099 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7100 mDispatcher->notifyKey(&keyArgs);
7101 window->assertNoEvents();
7102
7103 NotifyMotionArgs motionArgs =
7104 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7105 ADISPLAY_ID_DEFAULT);
7106 mDispatcher->notifyMotion(&motionArgs);
7107 window->assertNoEvents();
7108
7109 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007110 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7112
7113 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7114 mDispatcher->notifyKey(&keyArgs);
7115 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7116
7117 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7118 ADISPLAY_ID_DEFAULT);
7119 mDispatcher->notifyMotion(&motionArgs);
7120 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7121 window->assertNoEvents();
7122}
7123
7124TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
7125 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7126 std::make_shared<FakeApplicationHandle>();
7127 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007128 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7129 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007130 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7131 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007132 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007133 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007134 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7135 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007136 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007137 window->setOwnerInfo(222, 222);
7138 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7139 window->setFocusable(true);
7140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7141 setFocusedWindow(window);
7142 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7143
7144 // With the flag set, window should not get any input
7145 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7146 mDispatcher->notifyKey(&keyArgs);
7147 window->assertNoEvents();
7148
7149 NotifyMotionArgs motionArgs =
7150 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7151 ADISPLAY_ID_DEFAULT);
7152 mDispatcher->notifyMotion(&motionArgs);
7153 window->assertNoEvents();
7154
7155 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007156 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7158
7159 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7160 mDispatcher->notifyKey(&keyArgs);
7161 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7162
7163 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7164 ADISPLAY_ID_DEFAULT);
7165 mDispatcher->notifyMotion(&motionArgs);
7166 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
7167 window->assertNoEvents();
7168}
7169
7170TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
7171 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7172 std::make_shared<FakeApplicationHandle>();
7173 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007174 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7175 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007176 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7177 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007178 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007180 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7181 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007182 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007183 window->setOwnerInfo(222, 222);
7184 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7185 window->setFocusable(true);
7186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7187 setFocusedWindow(window);
7188 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7189
7190 // With the flag set, window should not get any input
7191 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7192 mDispatcher->notifyKey(&keyArgs);
7193 window->assertNoEvents();
7194
7195 NotifyMotionArgs motionArgs =
7196 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7197 ADISPLAY_ID_DEFAULT);
7198 mDispatcher->notifyMotion(&motionArgs);
7199 window->assertNoEvents();
7200
7201 // When the window is no longer obscured because it went on top, it should get input
7202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7203
7204 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7205 mDispatcher->notifyKey(&keyArgs);
7206 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7207
7208 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7209 ADISPLAY_ID_DEFAULT);
7210 mDispatcher->notifyMotion(&motionArgs);
7211 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7212 window->assertNoEvents();
7213}
7214
Antonio Kantekf16f2832021-09-28 04:39:20 +00007215class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7216protected:
7217 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007218 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007219 sp<FakeWindowHandle> mWindow;
7220 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007221 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007222
7223 void SetUp() override {
7224 InputDispatcherTest::SetUp();
7225
7226 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007227 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007228 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007229 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007230 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007231 mSecondWindow =
7232 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007233 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007234 mThirdWindow =
7235 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7236 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7237 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007238
7239 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7241 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7242 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007243 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007244
Antonio Kantek15beb512022-06-13 22:35:41 +00007245 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007246 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00007247 WINDOW_UID, true /* hasPermission */,
7248 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007249 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7250 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007251 mThirdWindow->assertNoEvents();
7252 }
7253
7254 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7255 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
7256 SECONDARY_WINDOW_UID, true /* hasPermission */,
7257 SECOND_DISPLAY_ID)) {
7258 mWindow->assertNoEvents();
7259 mSecondWindow->assertNoEvents();
7260 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007261 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007262 }
7263
Antonio Kantek15beb512022-06-13 22:35:41 +00007264 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7265 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007266 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7267 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007268 mWindow->consumeTouchModeEvent(inTouchMode);
7269 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007270 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007271 }
7272};
7273
Antonio Kantek26defcf2022-02-08 01:12:27 +00007274TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007275 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007276 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7277 windowInfo.ownerPid, windowInfo.ownerUid,
7278 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007279}
7280
Antonio Kantek26defcf2022-02-08 01:12:27 +00007281TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7282 const WindowInfo& windowInfo = *mWindow->getInfo();
7283 int32_t ownerPid = windowInfo.ownerPid;
7284 int32_t ownerUid = windowInfo.ownerUid;
7285 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7286 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007287 ownerUid, false /*hasPermission*/,
7288 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007289 mWindow->assertNoEvents();
7290 mSecondWindow->assertNoEvents();
7291}
7292
7293TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7294 const WindowInfo& windowInfo = *mWindow->getInfo();
7295 int32_t ownerPid = windowInfo.ownerPid;
7296 int32_t ownerUid = windowInfo.ownerUid;
7297 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007298 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
7299 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007300}
7301
Antonio Kantekf16f2832021-09-28 04:39:20 +00007302TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007303 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007304 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7305 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007306 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007307 mWindow->assertNoEvents();
7308 mSecondWindow->assertNoEvents();
7309}
7310
Antonio Kantek15beb512022-06-13 22:35:41 +00007311TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7312 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7313 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7314 windowInfo.ownerPid, windowInfo.ownerUid,
7315 true /*hasPermission*/, SECOND_DISPLAY_ID));
7316 mWindow->assertNoEvents();
7317 mSecondWindow->assertNoEvents();
7318 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7319}
7320
Antonio Kantek48710e42022-03-24 14:19:30 -07007321TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7322 // Interact with the window first.
7323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7324 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7325 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7326
7327 // Then remove focus.
7328 mWindow->setFocusable(false);
7329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7330
7331 // Assert that caller can switch touch mode by owning one of the last interacted window.
7332 const WindowInfo& windowInfo = *mWindow->getInfo();
7333 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7334 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007335 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007336}
7337
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007338class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7339public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007340 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007341 std::shared_ptr<FakeApplicationHandle> application =
7342 std::make_shared<FakeApplicationHandle>();
7343 std::string name = "Fake Spy ";
7344 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007345 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7346 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007347 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007348 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007349 return spy;
7350 }
7351
7352 sp<FakeWindowHandle> createForeground() {
7353 std::shared_ptr<FakeApplicationHandle> application =
7354 std::make_shared<FakeApplicationHandle>();
7355 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007356 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7357 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007358 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007359 return window;
7360 }
7361
7362private:
7363 int mSpyCount{0};
7364};
7365
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007366using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007367/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007368 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7369 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007370TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7371 ScopedSilentDeath _silentDeath;
7372
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007373 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007374 spy->setTrustedOverlay(false);
7375 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7376 ".* not a trusted overlay");
7377}
7378
7379/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007380 * Input injection into a display with a spy window but no foreground windows should succeed.
7381 */
7382TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007383 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007384 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7385
7386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7387 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7389 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7390}
7391
7392/**
7393 * Verify the order in which different input windows receive events. The touched foreground window
7394 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7395 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7396 * receive events before ones belows it.
7397 *
7398 * Here, we set up a scenario with four windows in the following Z order from the top:
7399 * spy1, spy2, window, spy3.
7400 * We then inject an event and verify that the foreground "window" receives it first, followed by
7401 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7402 * window.
7403 */
7404TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7405 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007406 auto spy1 = createSpy();
7407 auto spy2 = createSpy();
7408 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7410 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7411 const size_t numChannels = channels.size();
7412
Michael Wright8e9a8562022-02-09 13:44:29 +00007413 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007414 if (!epollFd.ok()) {
7415 FAIL() << "Failed to create epoll fd";
7416 }
7417
7418 for (size_t i = 0; i < numChannels; i++) {
7419 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7420 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7421 FAIL() << "Failed to add fd to epoll";
7422 }
7423 }
7424
7425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7426 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7427 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7428
7429 std::vector<size_t> eventOrder;
7430 std::vector<struct epoll_event> events(numChannels);
7431 for (;;) {
7432 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7433 (100ms).count());
7434 if (nFds < 0) {
7435 FAIL() << "Failed to call epoll_wait";
7436 }
7437 if (nFds == 0) {
7438 break; // epoll_wait timed out
7439 }
7440 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007441 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007442 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007443 channels[i]->consumeMotionDown();
7444 }
7445 }
7446
7447 // Verify the order in which the events were received.
7448 EXPECT_EQ(3u, eventOrder.size());
7449 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7450 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7451 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7452}
7453
7454/**
7455 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7456 */
7457TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7458 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007459 auto spy = createSpy();
7460 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7462
7463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7464 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7465 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7466 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7467 spy->assertNoEvents();
7468}
7469
7470/**
7471 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7472 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7473 * to the window.
7474 */
7475TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7476 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007477 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007478 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7480
7481 // Inject an event outside the spy window's touchable region.
7482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7483 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7484 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7485 window->consumeMotionDown();
7486 spy->assertNoEvents();
7487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7488 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7490 window->consumeMotionUp();
7491 spy->assertNoEvents();
7492
7493 // Inject an event inside the spy window's touchable region.
7494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7495 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7496 {5, 10}))
7497 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7498 window->consumeMotionDown();
7499 spy->consumeMotionDown();
7500}
7501
7502/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007503 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007504 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007505 */
7506TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7507 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007508 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007509 auto spy = createSpy();
7510 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007511 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007512 spy->setFrame(Rect{0, 0, 20, 20});
7513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7514
7515 // Inject an event outside the spy window's frame and touchable region.
7516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007517 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7518 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7520 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007521 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007522}
7523
7524/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007525 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7526 * pointers that are down within its bounds.
7527 */
7528TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7529 auto windowLeft = createForeground();
7530 windowLeft->setFrame({0, 0, 100, 200});
7531 auto windowRight = createForeground();
7532 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007533 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007534 spy->setFrame({0, 0, 200, 200});
7535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7536
7537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7538 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7539 {50, 50}))
7540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7541 windowLeft->consumeMotionDown();
7542 spy->consumeMotionDown();
7543
7544 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007545 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007546 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7547 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7548 .pointer(
7549 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7550 .build();
7551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7552 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7553 InputEventInjectionSync::WAIT_FOR_RESULT))
7554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7555 windowRight->consumeMotionDown();
7556 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7557}
7558
7559/**
7560 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7561 * the spy should receive the second pointer with ACTION_DOWN.
7562 */
7563TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7564 auto window = createForeground();
7565 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007566 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007567 spyRight->setFrame({100, 0, 200, 200});
7568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7569
7570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7571 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7572 {50, 50}))
7573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7574 window->consumeMotionDown();
7575 spyRight->assertNoEvents();
7576
7577 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007578 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007579 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7580 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7581 .pointer(
7582 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7583 .build();
7584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7585 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7586 InputEventInjectionSync::WAIT_FOR_RESULT))
7587 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7588 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7589 spyRight->consumeMotionDown();
7590}
7591
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007592/**
7593 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7594 * windows should be allowed to control split touch.
7595 */
7596TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007597 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007598 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007599 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007600 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007601
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007602 auto window = createForeground();
7603 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007604
7605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7606
7607 // First finger down, no window touched.
7608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7609 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7610 {100, 200}))
7611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7612 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7613 window->assertNoEvents();
7614
7615 // Second finger down on window, the window should receive touch down.
7616 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007617 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007618 .displayId(ADISPLAY_ID_DEFAULT)
7619 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7620 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7621 .x(100)
7622 .y(200))
7623 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7624 .build();
7625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7626 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7627 InputEventInjectionSync::WAIT_FOR_RESULT))
7628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7629
7630 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7631 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7632}
7633
7634/**
7635 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7636 * do not receive key events.
7637 */
7638TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007639 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007640 spy->setFocusable(false);
7641
7642 auto window = createForeground();
7643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7644 setFocusedWindow(window);
7645 window->consumeFocusEvent(true);
7646
7647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7648 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7649 window->consumeKeyDown(ADISPLAY_ID_NONE);
7650
7651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7652 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7653 window->consumeKeyUp(ADISPLAY_ID_NONE);
7654
7655 spy->assertNoEvents();
7656}
7657
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007658using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7659
7660/**
7661 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7662 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7663 */
7664TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7665 auto window = createForeground();
7666 auto spy1 = createSpy();
7667 auto spy2 = createSpy();
7668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7669
7670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7673 window->consumeMotionDown();
7674 spy1->consumeMotionDown();
7675 spy2->consumeMotionDown();
7676
7677 // Pilfer pointers from the second spy window.
7678 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7679 spy2->assertNoEvents();
7680 spy1->consumeMotionCancel();
7681 window->consumeMotionCancel();
7682
7683 // The rest of the gesture should only be sent to the second spy window.
7684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7685 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7686 ADISPLAY_ID_DEFAULT))
7687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7688 spy2->consumeMotionMove();
7689 spy1->assertNoEvents();
7690 window->assertNoEvents();
7691}
7692
7693/**
7694 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7695 * in the middle of the gesture.
7696 */
7697TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7698 auto window = createForeground();
7699 auto spy = createSpy();
7700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7701
7702 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7703 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7705 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7706 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7707
7708 window->releaseChannel();
7709
7710 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7711
7712 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7713 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7714 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7715 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7716}
7717
7718/**
7719 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7720 * the spy, but not to any other windows.
7721 */
7722TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7723 auto spy = createSpy();
7724 auto window = createForeground();
7725
7726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7727
7728 // First finger down on the window and the spy.
7729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7730 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7731 {100, 200}))
7732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7733 spy->consumeMotionDown();
7734 window->consumeMotionDown();
7735
7736 // Spy window pilfers the pointers.
7737 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7738 window->consumeMotionCancel();
7739
7740 // Second finger down on the window and spy, but the window should not receive the pointer down.
7741 const MotionEvent secondFingerDownEvent =
7742 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7743 .displayId(ADISPLAY_ID_DEFAULT)
7744 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7745 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7746 .x(100)
7747 .y(200))
7748 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7749 .build();
7750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7751 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7752 InputEventInjectionSync::WAIT_FOR_RESULT))
7753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7754
7755 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7756
7757 // Third finger goes down outside all windows, so injection should fail.
7758 const MotionEvent thirdFingerDownEvent =
7759 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7760 .displayId(ADISPLAY_ID_DEFAULT)
7761 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7762 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7763 .x(100)
7764 .y(200))
7765 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7766 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7767 .build();
7768 ASSERT_EQ(InputEventInjectionResult::FAILED,
7769 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7770 InputEventInjectionSync::WAIT_FOR_RESULT))
7771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7772
7773 spy->assertNoEvents();
7774 window->assertNoEvents();
7775}
7776
7777/**
7778 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7779 */
7780TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7781 auto spy = createSpy();
7782 spy->setFrame(Rect(0, 0, 100, 100));
7783 auto window = createForeground();
7784 window->setFrame(Rect(0, 0, 200, 200));
7785
7786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7787
7788 // First finger down on the window only
7789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7790 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7791 {150, 150}))
7792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7793 window->consumeMotionDown();
7794
7795 // Second finger down on the spy and window
7796 const MotionEvent secondFingerDownEvent =
7797 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7798 .displayId(ADISPLAY_ID_DEFAULT)
7799 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7800 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7801 .x(150)
7802 .y(150))
7803 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7804 .build();
7805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7806 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7807 InputEventInjectionSync::WAIT_FOR_RESULT))
7808 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7809 spy->consumeMotionDown();
7810 window->consumeMotionPointerDown(1);
7811
7812 // Third finger down on the spy and window
7813 const MotionEvent thirdFingerDownEvent =
7814 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7815 .displayId(ADISPLAY_ID_DEFAULT)
7816 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7817 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7818 .x(150)
7819 .y(150))
7820 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7821 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7822 .build();
7823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7824 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7825 InputEventInjectionSync::WAIT_FOR_RESULT))
7826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7827 spy->consumeMotionPointerDown(1);
7828 window->consumeMotionPointerDown(2);
7829
7830 // Spy window pilfers the pointers.
7831 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7832 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7833 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7834
7835 spy->assertNoEvents();
7836 window->assertNoEvents();
7837}
7838
7839/**
7840 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7841 * other windows should be canceled. If this results in the cancellation of all pointers for some
7842 * window, then that window should receive ACTION_CANCEL.
7843 */
7844TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7845 auto spy = createSpy();
7846 spy->setFrame(Rect(0, 0, 100, 100));
7847 auto window = createForeground();
7848 window->setFrame(Rect(0, 0, 200, 200));
7849
7850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7851
7852 // First finger down on both spy and window
7853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7854 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7855 {10, 10}))
7856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7857 window->consumeMotionDown();
7858 spy->consumeMotionDown();
7859
7860 // Second finger down on the spy and window
7861 const MotionEvent secondFingerDownEvent =
7862 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7863 .displayId(ADISPLAY_ID_DEFAULT)
7864 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7865 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7866 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7867 .build();
7868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7869 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7870 InputEventInjectionSync::WAIT_FOR_RESULT))
7871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7872 spy->consumeMotionPointerDown(1);
7873 window->consumeMotionPointerDown(1);
7874
7875 // Spy window pilfers the pointers.
7876 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7877 window->consumeMotionCancel();
7878
7879 spy->assertNoEvents();
7880 window->assertNoEvents();
7881}
7882
7883/**
7884 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7885 * be sent to other windows
7886 */
7887TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7888 auto spy = createSpy();
7889 spy->setFrame(Rect(0, 0, 100, 100));
7890 auto window = createForeground();
7891 window->setFrame(Rect(0, 0, 200, 200));
7892
7893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7894
7895 // First finger down on both window and spy
7896 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7897 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7898 {10, 10}))
7899 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7900 window->consumeMotionDown();
7901 spy->consumeMotionDown();
7902
7903 // Spy window pilfers the pointers.
7904 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7905 window->consumeMotionCancel();
7906
7907 // Second finger down on the window only
7908 const MotionEvent secondFingerDownEvent =
7909 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7910 .displayId(ADISPLAY_ID_DEFAULT)
7911 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7912 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7913 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7914 .x(150)
7915 .y(150))
7916 .build();
7917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7918 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7919 InputEventInjectionSync::WAIT_FOR_RESULT))
7920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7921 window->consumeMotionDown();
7922 window->assertNoEvents();
7923
7924 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7925 spy->consumeMotionMove();
7926 spy->assertNoEvents();
7927}
7928
Prabir Pradhand65552b2021-10-07 11:23:50 -07007929class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7930public:
7931 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7932 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7933 std::make_shared<FakeApplicationHandle>();
7934 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007935 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7936 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007937 overlay->setFocusable(false);
7938 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007939 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007940 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007941 overlay->setTrustedOverlay(true);
7942
7943 std::shared_ptr<FakeApplicationHandle> application =
7944 std::make_shared<FakeApplicationHandle>();
7945 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007946 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7947 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007948 window->setFocusable(true);
7949 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007950
7951 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7953 setFocusedWindow(window);
7954 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7955 return {std::move(overlay), std::move(window)};
7956 }
7957
7958 void sendFingerEvent(int32_t action) {
7959 NotifyMotionArgs motionArgs =
7960 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7961 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7962 mDispatcher->notifyMotion(&motionArgs);
7963 }
7964
7965 void sendStylusEvent(int32_t action) {
7966 NotifyMotionArgs motionArgs =
7967 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7968 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7969 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7970 mDispatcher->notifyMotion(&motionArgs);
7971 }
7972};
7973
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007974using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7975
7976TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7977 ScopedSilentDeath _silentDeath;
7978
Prabir Pradhand65552b2021-10-07 11:23:50 -07007979 auto [overlay, window] = setupStylusOverlayScenario();
7980 overlay->setTrustedOverlay(false);
7981 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7982 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7983 ".* not a trusted overlay");
7984}
7985
7986TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7987 auto [overlay, window] = setupStylusOverlayScenario();
7988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7989
7990 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7991 overlay->consumeMotionDown();
7992 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7993 overlay->consumeMotionUp();
7994
7995 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7996 window->consumeMotionDown();
7997 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7998 window->consumeMotionUp();
7999
8000 overlay->assertNoEvents();
8001 window->assertNoEvents();
8002}
8003
8004TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
8005 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008006 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8008
8009 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8010 overlay->consumeMotionDown();
8011 window->consumeMotionDown();
8012 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8013 overlay->consumeMotionUp();
8014 window->consumeMotionUp();
8015
8016 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8017 window->consumeMotionDown();
8018 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8019 window->consumeMotionUp();
8020
8021 overlay->assertNoEvents();
8022 window->assertNoEvents();
8023}
8024
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00008025/**
8026 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
8027 * The scenario is as follows:
8028 * - The stylus interceptor overlay is configured as a spy window.
8029 * - The stylus interceptor spy receives the start of a new stylus gesture.
8030 * - It pilfers pointers and then configures itself to no longer be a spy.
8031 * - The stylus interceptor continues to receive the rest of the gesture.
8032 */
8033TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
8034 auto [overlay, window] = setupStylusOverlayScenario();
8035 overlay->setSpy(true);
8036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8037
8038 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8039 overlay->consumeMotionDown();
8040 window->consumeMotionDown();
8041
8042 // The interceptor pilfers the pointers.
8043 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
8044 window->consumeMotionCancel();
8045
8046 // The interceptor configures itself so that it is no longer a spy.
8047 overlay->setSpy(false);
8048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8049
8050 // It continues to receive the rest of the stylus gesture.
8051 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
8052 overlay->consumeMotionMove();
8053 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8054 overlay->consumeMotionUp();
8055
8056 window->assertNoEvents();
8057}
8058
Prabir Pradhan5735a322022-04-11 17:23:34 +00008059struct User {
8060 int32_t mPid;
8061 int32_t mUid;
8062 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
8063 std::unique_ptr<InputDispatcher>& mDispatcher;
8064
8065 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
8066 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
8067
8068 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
8069 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
8070 ADISPLAY_ID_DEFAULT, {100, 200},
8071 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
8072 AMOTION_EVENT_INVALID_CURSOR_POSITION},
8073 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
8074 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
8075 }
8076
8077 InputEventInjectionResult injectTargetedKey(int32_t action) const {
8078 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
8079 InputEventInjectionSync::WAIT_FOR_RESULT,
8080 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
8081 mPolicyFlags);
8082 }
8083
8084 sp<FakeWindowHandle> createWindow() const {
8085 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8086 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008087 sp<FakeWindowHandle> window =
8088 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
8089 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00008090 window->setOwnerInfo(mPid, mUid);
8091 return window;
8092 }
8093};
8094
8095using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
8096
8097TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
8098 auto owner = User(mDispatcher, 10, 11);
8099 auto window = owner.createWindow();
8100 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8101
8102 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8103 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8104 window->consumeMotionDown();
8105
8106 setFocusedWindow(window);
8107 window->consumeFocusEvent(true);
8108
8109 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8110 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8111 window->consumeKeyDown(ADISPLAY_ID_NONE);
8112}
8113
8114TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
8115 auto owner = User(mDispatcher, 10, 11);
8116 auto window = owner.createWindow();
8117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8118
8119 auto rando = User(mDispatcher, 20, 21);
8120 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8121 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8122
8123 setFocusedWindow(window);
8124 window->consumeFocusEvent(true);
8125
8126 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8127 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8128 window->assertNoEvents();
8129}
8130
8131TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
8132 auto owner = User(mDispatcher, 10, 11);
8133 auto window = owner.createWindow();
8134 auto spy = owner.createWindow();
8135 spy->setSpy(true);
8136 spy->setTrustedOverlay(true);
8137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8138
8139 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8140 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8141 spy->consumeMotionDown();
8142 window->consumeMotionDown();
8143}
8144
8145TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
8146 auto owner = User(mDispatcher, 10, 11);
8147 auto window = owner.createWindow();
8148
8149 auto rando = User(mDispatcher, 20, 21);
8150 auto randosSpy = rando.createWindow();
8151 randosSpy->setSpy(true);
8152 randosSpy->setTrustedOverlay(true);
8153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8154
8155 // The event is targeted at owner's window, so injection should succeed, but the spy should
8156 // not receive the event.
8157 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8158 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8159 randosSpy->assertNoEvents();
8160 window->consumeMotionDown();
8161}
8162
8163TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
8164 auto owner = User(mDispatcher, 10, 11);
8165 auto window = owner.createWindow();
8166
8167 auto rando = User(mDispatcher, 20, 21);
8168 auto randosSpy = rando.createWindow();
8169 randosSpy->setSpy(true);
8170 randosSpy->setTrustedOverlay(true);
8171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8172
8173 // A user that has injection permission can inject into any window.
8174 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8175 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8176 ADISPLAY_ID_DEFAULT));
8177 randosSpy->consumeMotionDown();
8178 window->consumeMotionDown();
8179
8180 setFocusedWindow(randosSpy);
8181 randosSpy->consumeFocusEvent(true);
8182
8183 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
8184 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
8185 window->assertNoEvents();
8186}
8187
8188TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
8189 auto owner = User(mDispatcher, 10, 11);
8190 auto window = owner.createWindow();
8191
8192 auto rando = User(mDispatcher, 20, 21);
8193 auto randosWindow = rando.createWindow();
8194 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8195 randosWindow->setWatchOutsideTouch(true);
8196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8197
8198 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8199 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8200 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8201 window->consumeMotionDown();
8202 randosWindow->consumeMotionOutside();
8203}
8204
Garfield Tane84e6f92019-08-29 17:28:41 -07008205} // namespace android::inputdispatcher