blob: dfe3d16e751097ca8ac6dc2c70c5e5600609b7a5 [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 Vishniakou1ae72f12023-01-29 12:55:30 -080061static constexpr int32_t ACTION_CANCEL = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080062static constexpr int32_t POINTER_1_DOWN =
63 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000064static constexpr int32_t POINTER_2_DOWN =
65 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000066static constexpr int32_t POINTER_3_DOWN =
67 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Arthur Hungc539dbb2022-12-08 07:45:36 +000068static constexpr int32_t POINTER_0_UP =
69 AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080070static constexpr int32_t POINTER_1_UP =
71 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
72
Antonio Kantek15beb512022-06-13 22:35:41 +000073// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000074static constexpr int32_t WINDOW_PID = 999;
75static constexpr int32_t WINDOW_UID = 1001;
76
Antonio Kantek15beb512022-06-13 22:35:41 +000077// The default pid and uid for the windows created on the secondary display by the test.
78static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
79static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
80
Prabir Pradhan5735a322022-04-11 17:23:34 +000081// The default policy flags to use for event injection by tests.
82static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000084// An arbitrary pid of the gesture monitor window
85static constexpr int32_t MONITOR_PID = 2001;
86
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080087static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
88
Arthur Hungc539dbb2022-12-08 07:45:36 +000089static constexpr int expectedWallpaperFlags =
90 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
91
chaviwd1c23182019-12-20 18:44:56 -080092struct PointF {
93 float x;
94 float y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080095 auto operator<=>(const PointF&) const = default;
chaviwd1c23182019-12-20 18:44:56 -080096};
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Gang Wang342c9272020-01-13 13:15:04 -050098/**
99 * Return a DOWN key event with KEYCODE_A.
100 */
101static KeyEvent getTestKeyEvent() {
102 KeyEvent event;
103
Garfield Tanfbe732e2020-01-24 11:26:14 -0800104 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
105 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
106 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -0500107 return event;
108}
109
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000110static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
111 ASSERT_EQ(expectedAction, receivedAction)
112 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
113 << MotionEvent::actionToString(receivedAction);
114}
115
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800116MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
117 bool matches = action == arg.getAction();
118 if (!matches) {
119 *result_listener << "expected action " << MotionEvent::actionToString(action)
120 << ", but got " << MotionEvent::actionToString(arg.getAction());
121 }
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800122 if (action == AMOTION_EVENT_ACTION_DOWN) {
123 if (!matches) {
124 *result_listener << "; ";
125 }
126 *result_listener << "downTime should match eventTime for ACTION_DOWN events";
127 matches &= arg.getDownTime() == arg.getEventTime();
128 }
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800129 if (action == AMOTION_EVENT_ACTION_CANCEL) {
130 if (!matches) {
131 *result_listener << "; ";
132 }
133 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
134 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
135 }
136 return matches;
137}
138
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800139MATCHER_P(WithDownTime, downTime, "InputEvent with specified downTime") {
140 return arg.getDownTime() == downTime;
141}
142
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800143MATCHER_P(WithDisplayId, displayId, "InputEvent with specified displayId") {
144 return arg.getDisplayId() == displayId;
145}
146
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800147MATCHER_P(WithSource, source, "InputEvent with specified source") {
148 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
149 << inputEventSourceToString(arg.getSource());
150 return arg.getSource() == source;
151}
152
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800153MATCHER_P(WithFlags, flags, "InputEvent with specified flags") {
154 return arg.getFlags() == flags;
155}
156
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800157MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
158 if (arg.getPointerCount() != 1) {
159 *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
160 return false;
161 }
162 return arg.getX(0 /*pointerIndex*/) == x && arg.getY(0 /*pointerIndex*/) == y;
163}
164
165MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
166 // Build a map for the received pointers, by pointer id
167 std::map<int32_t /*pointerId*/, PointF> actualPointers;
168 for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
169 const int32_t pointerId = arg.getPointerId(pointerIndex);
170 actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
171 }
172 return pointers == actualPointers;
173}
174
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175// --- FakeInputDispatcherPolicy ---
176
177class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
178 InputDispatcherConfiguration mConfig;
179
Prabir Pradhanedd96402022-02-15 01:46:16 -0800180 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
181
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000183 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184
185public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000186 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800187
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800188 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700189 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
190 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
191 EXPECT_EQ(event.getDisplayId(), args.displayId);
192
193 const auto& keyEvent = static_cast<const KeyEvent&>(event);
194 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
195 EXPECT_EQ(keyEvent.getAction(), args.action);
196 });
Jackal Guof9696682018-10-05 12:23:23 +0800197 }
198
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700199 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
200 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
201 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
202 EXPECT_EQ(event.getDisplayId(), args.displayId);
203
204 const auto& motionEvent = static_cast<const MotionEvent&>(event);
205 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
206 EXPECT_EQ(motionEvent.getAction(), args.action);
207 EXPECT_EQ(motionEvent.getX(0), point.x);
208 EXPECT_EQ(motionEvent.getY(0), point.y);
209 EXPECT_EQ(motionEvent.getRawX(0), point.x);
210 EXPECT_EQ(motionEvent.getRawY(0), point.y);
211 });
Jackal Guof9696682018-10-05 12:23:23 +0800212 }
213
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700214 void assertFilterInputEventWasNotCalled() {
215 std::scoped_lock lock(mLock);
216 ASSERT_EQ(nullptr, mFilteredEvent);
217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800219 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700220 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800221 ASSERT_TRUE(mConfigurationChangedTime)
222 << "Timed out waiting for configuration changed call";
223 ASSERT_EQ(*mConfigurationChangedTime, when);
224 mConfigurationChangedTime = std::nullopt;
225 }
226
227 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700228 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800229 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800230 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800231 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
232 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
233 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
234 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
235 mLastNotifySwitch = std::nullopt;
236 }
237
chaviwfd6d3512019-03-25 13:23:49 -0700238 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700239 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800240 ASSERT_EQ(touchedToken, mOnPointerDownToken);
241 mOnPointerDownToken.clear();
242 }
243
244 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700245 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800246 ASSERT_TRUE(mOnPointerDownToken == nullptr)
247 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700248 }
249
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700250 // This function must be called soon after the expected ANR timer starts,
251 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500252 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700253 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500254 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800255 std::unique_lock lock(mLock);
256 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500257 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800258 ASSERT_NO_FATAL_FAILURE(
259 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500260 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700261 }
262
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000263 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800264 const sp<WindowInfoHandle>& window) {
265 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
266 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
267 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500268 }
269
Prabir Pradhanedd96402022-02-15 01:46:16 -0800270 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
271 const sp<IBinder>& expectedToken,
272 int32_t expectedPid) {
273 std::unique_lock lock(mLock);
274 android::base::ScopedLockAssertion assumeLocked(mLock);
275 AnrResult result;
276 ASSERT_NO_FATAL_FAILURE(result =
277 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
278 const auto& [token, pid] = result;
279 ASSERT_EQ(expectedToken, token);
280 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500281 }
282
Prabir Pradhanedd96402022-02-15 01:46:16 -0800283 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000284 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500285 std::unique_lock lock(mLock);
286 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800287 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
288 const auto& [token, _] = result;
289 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000290 }
291
Prabir Pradhanedd96402022-02-15 01:46:16 -0800292 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
293 int32_t expectedPid) {
294 std::unique_lock lock(mLock);
295 android::base::ScopedLockAssertion assumeLocked(mLock);
296 AnrResult result;
297 ASSERT_NO_FATAL_FAILURE(
298 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
299 const auto& [token, pid] = result;
300 ASSERT_EQ(expectedToken, token);
301 ASSERT_EQ(expectedPid, pid);
302 }
303
304 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000305 sp<IBinder> getResponsiveWindowToken() {
306 std::unique_lock lock(mLock);
307 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800308 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
309 const auto& [token, _] = result;
310 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700311 }
312
313 void assertNotifyAnrWasNotCalled() {
314 std::scoped_lock lock(mLock);
315 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800316 ASSERT_TRUE(mAnrWindows.empty());
317 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500318 << "ANR was not called, but please also consume the 'connection is responsive' "
319 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700320 }
321
Garfield Tan1c7bc862020-01-28 13:24:04 -0800322 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
323 mConfig.keyRepeatTimeout = timeout;
324 mConfig.keyRepeatDelay = delay;
325 }
326
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000327 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800328 std::unique_lock lock(mLock);
329 base::ScopedLockAssertion assumeLocked(mLock);
330
331 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
332 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000333 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800334 enabled;
335 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000336 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
337 << ") to be called.";
338 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800339 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000340 auto request = *mPointerCaptureRequest;
341 mPointerCaptureRequest.reset();
342 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800343 }
344
345 void assertSetPointerCaptureNotCalled() {
346 std::unique_lock lock(mLock);
347 base::ScopedLockAssertion assumeLocked(mLock);
348
349 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000350 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800351 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000352 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800353 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000354 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800355 }
356
arthurhungf452d0b2021-01-06 00:19:52 +0800357 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
358 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800359 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800360 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800361 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800362 }
363
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800364 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
365 std::unique_lock lock(mLock);
366 base::ScopedLockAssertion assumeLocked(mLock);
367 std::optional<sp<IBinder>> receivedToken =
368 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
369 mNotifyInputChannelBroken);
370 ASSERT_TRUE(receivedToken.has_value());
371 ASSERT_EQ(token, *receivedToken);
372 }
373
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800374 /**
375 * Set policy timeout. A value of zero means next key will not be intercepted.
376 */
377 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
378 mInterceptKeyTimeout = timeout;
379 }
380
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700382 std::mutex mLock;
383 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
384 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
385 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
386 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800387
Prabir Pradhan99987712020-11-10 18:43:05 -0800388 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000389
390 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800391
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700392 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700393 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800394 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
395 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700396 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800397 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
398 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700399
arthurhungf452d0b2021-01-06 00:19:52 +0800400 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800401 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800402
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800403 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
404
Prabir Pradhanedd96402022-02-15 01:46:16 -0800405 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
406 // for a specific container to become non-empty. When the container is non-empty, return the
407 // first entry from the container and erase it.
408 template <class T>
409 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
410 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
411 // If there is an ANR, Dispatcher won't be idle because there are still events
412 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
413 // before checking if ANR was called.
414 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
415 // to provide it some time to act. 100ms seems reasonable.
416 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
417 const std::chrono::time_point start = std::chrono::steady_clock::now();
418 std::optional<T> token =
419 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
420 if (!token.has_value()) {
421 ADD_FAILURE() << "Did not receive the ANR callback";
422 return {};
423 }
424
425 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
426 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
427 // the dispatcher started counting before this function was called
428 if (std::chrono::abs(timeout - waited) > 100ms) {
429 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
430 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
431 << "ms, but waited "
432 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
433 << "ms instead";
434 }
435 return *token;
436 }
437
438 template <class T>
439 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
440 std::queue<T>& storage,
441 std::unique_lock<std::mutex>& lock,
442 std::condition_variable& condition)
443 REQUIRES(mLock) {
444 condition.wait_for(lock, timeout,
445 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
446 if (storage.empty()) {
447 ADD_FAILURE() << "Did not receive the expected callback";
448 return std::nullopt;
449 }
450 T item = storage.front();
451 storage.pop();
452 return std::make_optional(item);
453 }
454
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600455 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700456 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800457 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 }
459
Prabir Pradhanedd96402022-02-15 01:46:16 -0800460 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
461 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700462 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800463 ASSERT_TRUE(pid.has_value());
464 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700465 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500466 }
467
Prabir Pradhanedd96402022-02-15 01:46:16 -0800468 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
469 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500470 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800471 ASSERT_TRUE(pid.has_value());
472 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500473 mNotifyAnr.notify_all();
474 }
475
476 void notifyNoFocusedWindowAnr(
477 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
478 std::scoped_lock lock(mLock);
479 mAnrApplications.push(applicationHandle);
480 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 }
482
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800483 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
484 std::scoped_lock lock(mLock);
485 mBrokenInputChannels.push(connectionToken);
486 mNotifyInputChannelBroken.notify_all();
487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600489 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700490
Chris Yef59a2f42020-10-16 12:55:26 -0700491 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
492 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
493 const std::vector<float>& values) override {}
494
495 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
496 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000497
Chris Yefb552902021-02-03 17:18:37 -0800498 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
499
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600500 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 *outConfig = mConfig;
502 }
503
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600504 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700505 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800506 switch (inputEvent->getType()) {
507 case AINPUT_EVENT_TYPE_KEY: {
508 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800509 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800510 break;
511 }
512
513 case AINPUT_EVENT_TYPE_MOTION: {
514 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800515 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800516 break;
517 }
518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 return true;
520 }
521
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800522 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
523 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
524 // Clear intercept state when we handled the event.
525 mInterceptKeyTimeout = 0ms;
526 }
527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600529 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600531 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800532 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
533 // Clear intercept state so we could dispatch the event in next wake.
534 mInterceptKeyTimeout = 0ms;
535 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 }
537
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600538 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 return false;
540 }
541
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600542 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
543 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700544 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800545 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
546 * essentially a passthrough for notifySwitch.
547 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800548 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 }
550
Sean Stoutb4e0a592021-02-23 07:34:53 -0800551 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600553 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700554 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700555 mOnPointerDownToken = newToken;
556 }
557
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000558 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800559 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000560 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800561 mPointerCaptureChangedCondition.notify_all();
562 }
563
arthurhungf452d0b2021-01-06 00:19:52 +0800564 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
565 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800566 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800567 mDropTargetWindowToken = token;
568 }
569
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700570 void assertFilterInputEventWasCalledInternal(
571 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700572 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800573 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700574 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800575 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577};
578
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579// --- InputDispatcherTest ---
580
581class InputDispatcherTest : public testing::Test {
582protected:
583 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700584 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000586 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700587 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800588 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800589 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000590 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 }
593
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000594 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700597 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700599
600 /**
601 * Used for debugging when writing the test
602 */
603 void dumpDispatcherState() {
604 std::string dump;
605 mDispatcher->dump(dump);
606 std::stringstream ss(dump);
607 std::string to;
608
609 while (std::getline(ss, to, '\n')) {
610 ALOGE("%s", to.c_str());
611 }
612 }
Vishnu Nair958da932020-08-21 17:12:37 -0700613
chaviw3277faf2021-05-19 16:45:23 -0500614 void setFocusedWindow(const sp<WindowInfoHandle>& window,
615 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700616 FocusRequest request;
617 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000618 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700619 if (focusedWindow) {
620 request.focusedToken = focusedWindow->getToken();
621 }
622 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
623 request.displayId = window->getInfo()->displayId;
624 mDispatcher->setFocusedWindow(request);
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626};
627
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
629 KeyEvent event;
630
631 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800632 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
633 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600634 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
635 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 undefined action.";
640
641 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800642 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
643 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600644 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800645 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000646 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
647 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 << "Should reject key events with ACTION_MULTIPLE.";
649}
650
651TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
652 MotionEvent event;
653 PointerProperties pointerProperties[MAX_POINTERS + 1];
654 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800655 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 pointerProperties[i].clear();
657 pointerProperties[i].id = i;
658 pointerCoords[i].clear();
659 }
660
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800661 // Some constants commonly used below
662 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
663 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
664 constexpr int32_t metaState = AMETA_NONE;
665 constexpr MotionClassification classification = MotionClassification::NONE;
666
chaviw9eaa22c2020-07-01 16:21:27 -0700667 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800669 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700670 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
671 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700672 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
673 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700674 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800675 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000676 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
677 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 << "Should reject motion events with undefined action.";
679
680 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800681 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800682 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
683 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
684 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
685 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500686 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800687 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000688 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
689 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 << "Should reject motion events with pointer down index too large.";
691
Garfield Tanfbe732e2020-01-24 11:26:14 -0800692 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 AMOTION_EVENT_ACTION_POINTER_DOWN |
694 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700695 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
696 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700697 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500698 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800699 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000700 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
701 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 << "Should reject motion events with pointer down index too small.";
703
704 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800705 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800706 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
707 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
708 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
709 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500710 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800711 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000712 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
713 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 << "Should reject motion events with pointer up index too large.";
715
Garfield Tanfbe732e2020-01-24 11:26:14 -0800716 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700717 AMOTION_EVENT_ACTION_POINTER_UP |
718 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700719 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
720 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700721 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500722 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800723 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000724 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
725 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 << "Should reject motion events with pointer up index too small.";
727
728 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800729 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
730 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700731 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700732 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
733 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700734 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800735 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000736 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
737 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 << "Should reject motion events with 0 pointers.";
739
Garfield Tanfbe732e2020-01-24 11:26:14 -0800740 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
741 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700742 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700743 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
744 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700745 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800746 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000747 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
748 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 << "Should reject motion events with more than MAX_POINTERS pointers.";
750
751 // Rejects motion events with invalid pointer ids.
752 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800753 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
754 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700755 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700756 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
757 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700758 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800759 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000760 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
761 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 << "Should reject motion events with pointer ids less than 0.";
763
764 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800765 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
766 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700767 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700768 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
769 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700770 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800771 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000772 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
773 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
775
776 // Rejects motion events with duplicate pointer ids.
777 pointerProperties[0].id = 1;
778 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800779 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
780 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700781 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700782 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
783 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700784 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800785 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000786 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
787 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 << "Should reject motion events with duplicate pointer ids.";
789}
790
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800791/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
792
793TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
794 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800795 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800796 mDispatcher->notifyConfigurationChanged(&args);
797 ASSERT_TRUE(mDispatcher->waitForIdle());
798
799 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
800}
801
802TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800803 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
804 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800805 mDispatcher->notifySwitch(&args);
806
807 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
808 args.policyFlags |= POLICY_FLAG_TRUSTED;
809 mFakePolicy->assertNotifySwitchWasCalled(args);
810}
811
Arthur Hungb92218b2018-08-14 12:00:21 +0800812// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700813static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700814// Default input dispatching timeout if there is no focused application or paused window
815// from which to determine an appropriate dispatching timeout.
816static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
817 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
818 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800819
820class FakeApplicationHandle : public InputApplicationHandle {
821public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700822 FakeApplicationHandle() {
823 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700824 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500825 mInfo.dispatchingTimeoutMillis =
826 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700827 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800828 virtual ~FakeApplicationHandle() {}
829
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000830 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700831
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500832 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
833 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700834 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800835};
836
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800837class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800838public:
Garfield Tan15601662020-09-22 15:32:38 -0700839 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800840 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700841 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800842 }
843
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800844 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700845 InputEvent* event;
846 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
847 if (!consumeSeq) {
848 return nullptr;
849 }
850 finishEvent(*consumeSeq);
851 return event;
852 }
853
854 /**
855 * Receive an event without acknowledging it.
856 * Return the sequence number that could later be used to send finished signal.
857 */
858 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800859 uint32_t consumeSeq;
860 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800861
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800862 std::chrono::time_point start = std::chrono::steady_clock::now();
863 status_t status = WOULD_BLOCK;
864 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800865 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800866 &event);
867 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
868 if (elapsed > 100ms) {
869 break;
870 }
871 }
872
873 if (status == WOULD_BLOCK) {
874 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700875 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800876 }
877
878 if (status != OK) {
879 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700880 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800881 }
882 if (event == nullptr) {
883 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700884 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800885 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700886 if (outEvent != nullptr) {
887 *outEvent = event;
888 }
889 return consumeSeq;
890 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800891
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700892 /**
893 * To be used together with "receiveEvent" to complete the consumption of an event.
894 */
895 void finishEvent(uint32_t consumeSeq) {
896 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
897 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800898 }
899
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000900 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
901 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
902 ASSERT_EQ(OK, status);
903 }
904
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000905 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
906 std::optional<int32_t> expectedDisplayId,
907 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800908 InputEvent* event = consume();
909
910 ASSERT_NE(nullptr, event) << mName.c_str()
911 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800912 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800914 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800915
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000916 if (expectedDisplayId.has_value()) {
917 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
918 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800919
Tiger Huang8664f8c2018-10-11 19:14:35 +0800920 switch (expectedEventType) {
921 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800922 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
923 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000924 if (expectedFlags.has_value()) {
925 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
926 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800927 break;
928 }
929 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800930 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000931 assertMotionAction(expectedAction, motionEvent.getAction());
932
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000933 if (expectedFlags.has_value()) {
934 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
935 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800936 break;
937 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100938 case AINPUT_EVENT_TYPE_FOCUS: {
939 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
940 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800941 case AINPUT_EVENT_TYPE_CAPTURE: {
942 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
943 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000944 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
945 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
946 }
arthurhungb89ccb02020-12-30 16:19:01 +0800947 case AINPUT_EVENT_TYPE_DRAG: {
948 FAIL() << "Use 'consumeDragEvent' for DRAG events";
949 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800950 default: {
951 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
952 }
953 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800954 }
955
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800956 MotionEvent* consumeMotion() {
957 InputEvent* event = consume();
958
959 if (event == nullptr) {
960 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
961 return nullptr;
962 }
963
964 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
965 ADD_FAILURE() << mName << " expected a MotionEvent, got "
966 << inputEventTypeToString(event->getType()) << " event";
967 return nullptr;
968 }
969 return static_cast<MotionEvent*>(event);
970 }
971
972 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
973 MotionEvent* motionEvent = consumeMotion();
974 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
975 ASSERT_THAT(*motionEvent, matcher);
976 }
977
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100978 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
979 InputEvent* event = consume();
980 ASSERT_NE(nullptr, event) << mName.c_str()
981 << ": consumer should have returned non-NULL event.";
982 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
983 << "Got " << inputEventTypeToString(event->getType())
984 << " event instead of FOCUS event";
985
986 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
987 << mName.c_str() << ": event displayId should always be NONE.";
988
989 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
990 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100991 }
992
Prabir Pradhan99987712020-11-10 18:43:05 -0800993 void consumeCaptureEvent(bool hasCapture) {
994 const InputEvent* event = consume();
995 ASSERT_NE(nullptr, event) << mName.c_str()
996 << ": consumer should have returned non-NULL event.";
997 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
998 << "Got " << inputEventTypeToString(event->getType())
999 << " event instead of CAPTURE event";
1000
1001 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1002 << mName.c_str() << ": event displayId should always be NONE.";
1003
1004 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1005 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1006 }
1007
arthurhungb89ccb02020-12-30 16:19:01 +08001008 void consumeDragEvent(bool isExiting, float x, float y) {
1009 const InputEvent* event = consume();
1010 ASSERT_NE(nullptr, event) << mName.c_str()
1011 << ": consumer should have returned non-NULL event.";
1012 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1013 << "Got " << inputEventTypeToString(event->getType())
1014 << " event instead of DRAG event";
1015
1016 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1017 << mName.c_str() << ": event displayId should always be NONE.";
1018
1019 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1020 EXPECT_EQ(isExiting, dragEvent.isExiting());
1021 EXPECT_EQ(x, dragEvent.getX());
1022 EXPECT_EQ(y, dragEvent.getY());
1023 }
1024
Antonio Kantekf16f2832021-09-28 04:39:20 +00001025 void consumeTouchModeEvent(bool inTouchMode) {
1026 const InputEvent* event = consume();
1027 ASSERT_NE(nullptr, event) << mName.c_str()
1028 << ": consumer should have returned non-NULL event.";
1029 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1030 << "Got " << inputEventTypeToString(event->getType())
1031 << " event instead of TOUCH_MODE event";
1032
1033 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1034 << mName.c_str() << ": event displayId should always be NONE.";
1035 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1036 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1037 }
1038
chaviwd1c23182019-12-20 18:44:56 -08001039 void assertNoEvents() {
1040 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001041 if (event == nullptr) {
1042 return;
1043 }
1044 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1045 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1046 ADD_FAILURE() << "Received key event "
1047 << KeyEvent::actionToString(keyEvent.getAction());
1048 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1049 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1050 ADD_FAILURE() << "Received motion event "
1051 << MotionEvent::actionToString(motionEvent.getAction());
1052 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1053 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1054 ADD_FAILURE() << "Received focus event, hasFocus = "
1055 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001056 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1057 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1058 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1059 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001060 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1061 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1062 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1063 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001064 }
1065 FAIL() << mName.c_str()
1066 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001067 }
1068
1069 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1070
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001071 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1072
chaviwd1c23182019-12-20 18:44:56 -08001073protected:
1074 std::unique_ptr<InputConsumer> mConsumer;
1075 PreallocatedInputEventFactory mEventFactory;
1076
1077 std::string mName;
1078};
1079
chaviw3277faf2021-05-19 16:45:23 -05001080class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001081public:
1082 static const int32_t WIDTH = 600;
1083 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001084
Chris Yea209fde2020-07-22 13:54:51 -07001085 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001086 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001087 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001088 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001089 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001090 base::Result<std::unique_ptr<InputChannel>> channel =
1091 dispatcher->createInputChannel(name);
1092 token = (*channel)->getConnectionToken();
1093 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001094 }
1095
1096 inputApplicationHandle->updateInfo();
1097 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1098
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001099 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001100 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001101 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001102 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001103 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001104 mInfo.frameLeft = 0;
1105 mInfo.frameTop = 0;
1106 mInfo.frameRight = WIDTH;
1107 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001108 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001109 mInfo.globalScaleFactor = 1.0;
1110 mInfo.touchableRegion.clear();
1111 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001112 mInfo.ownerPid = WINDOW_PID;
1113 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001114 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001115 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001116 }
1117
Arthur Hungabbb9d82021-09-01 14:52:30 +00001118 sp<FakeWindowHandle> clone(
1119 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001120 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001121 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001122 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1123 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001124 return handle;
1125 }
1126
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001127 void setTouchable(bool touchable) {
1128 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1129 }
chaviwd1c23182019-12-20 18:44:56 -08001130
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001131 void setFocusable(bool focusable) {
1132 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1133 }
1134
1135 void setVisible(bool visible) {
1136 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1137 }
Vishnu Nair958da932020-08-21 17:12:37 -07001138
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001139 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001140 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001141 }
1142
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001143 void setPaused(bool paused) {
1144 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1145 }
1146
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001147 void setPreventSplitting(bool preventSplitting) {
1148 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001149 }
1150
1151 void setSlippery(bool slippery) {
1152 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1153 }
1154
1155 void setWatchOutsideTouch(bool watchOutside) {
1156 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1157 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001158
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001159 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1160
1161 void setInterceptsStylus(bool interceptsStylus) {
1162 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1163 }
1164
1165 void setDropInput(bool dropInput) {
1166 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1167 }
1168
1169 void setDropInputIfObscured(bool dropInputIfObscured) {
1170 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1171 }
1172
1173 void setNoInputChannel(bool noInputChannel) {
1174 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1175 }
1176
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001177 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1178
chaviw3277faf2021-05-19 16:45:23 -05001179 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001180
Bernardo Rufino7393d172021-02-26 13:56:11 +00001181 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1182
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001183 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001184 mInfo.frameLeft = frame.left;
1185 mInfo.frameTop = frame.top;
1186 mInfo.frameRight = frame.right;
1187 mInfo.frameBottom = frame.bottom;
1188 mInfo.touchableRegion.clear();
1189 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001190
1191 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1192 ui::Transform translate;
1193 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1194 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001195 }
1196
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001197 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1198
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001199 void setIsWallpaper(bool isWallpaper) {
1200 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1201 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001202
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001203 void setDupTouchToWallpaper(bool hasWallpaper) {
1204 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1205 }
chaviwd1c23182019-12-20 18:44:56 -08001206
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001207 void setTrustedOverlay(bool trustedOverlay) {
1208 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1209 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001210
chaviw9eaa22c2020-07-01 16:21:27 -07001211 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1212 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1213 }
1214
1215 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001216
yunho.shinf4a80b82020-11-16 21:13:57 +09001217 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1218
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001219 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1220 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1221 expectedFlags);
1222 }
1223
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1225 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1226 }
1227
Svet Ganov5d3bc372020-01-26 23:11:07 -08001228 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001229 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001230 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1231 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001232 }
1233
1234 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001235 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001236 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1237 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001238 }
1239
1240 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001241 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001242 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1243 }
1244
1245 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1246 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001247 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1248 expectedFlags);
1249 }
1250
Svet Ganov5d3bc372020-01-26 23:11:07 -08001251 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001252 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1253 int32_t expectedFlags = 0) {
1254 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1255 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001256 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1257 }
1258
1259 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001260 int32_t expectedFlags = 0) {
1261 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1262 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001263 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1264 }
1265
1266 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001267 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001268 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1269 expectedFlags);
1270 }
1271
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001272 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1273 int32_t expectedFlags = 0) {
1274 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1275 expectedFlags);
1276 }
1277
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001278 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1279 int32_t expectedFlags = 0) {
1280 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001281 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001282 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1283 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1284 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1285 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1286 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1287 }
1288
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001289 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1290 ASSERT_NE(mInputReceiver, nullptr)
1291 << "Cannot consume events from a window with no receiver";
1292 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1293 }
1294
Prabir Pradhan99987712020-11-10 18:43:05 -08001295 void consumeCaptureEvent(bool hasCapture) {
1296 ASSERT_NE(mInputReceiver, nullptr)
1297 << "Cannot consume events from a window with no receiver";
1298 mInputReceiver->consumeCaptureEvent(hasCapture);
1299 }
1300
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001301 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1302 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001303 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001304 ASSERT_THAT(*motionEvent, matcher);
1305 }
1306
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001307 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1308 std::optional<int32_t> expectedDisplayId,
1309 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001310 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1311 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1312 expectedFlags);
1313 }
1314
arthurhungb89ccb02020-12-30 16:19:01 +08001315 void consumeDragEvent(bool isExiting, float x, float y) {
1316 mInputReceiver->consumeDragEvent(isExiting, x, y);
1317 }
1318
Antonio Kantekf16f2832021-09-28 04:39:20 +00001319 void consumeTouchModeEvent(bool inTouchMode) {
1320 ASSERT_NE(mInputReceiver, nullptr)
1321 << "Cannot consume events from a window with no receiver";
1322 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1323 }
1324
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001325 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001326 if (mInputReceiver == nullptr) {
1327 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1328 return std::nullopt;
1329 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001330 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001331 }
1332
1333 void finishEvent(uint32_t sequenceNum) {
1334 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1335 mInputReceiver->finishEvent(sequenceNum);
1336 }
1337
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001338 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1339 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1340 mInputReceiver->sendTimeline(inputEventId, timeline);
1341 }
1342
chaviwaf87b3e2019-10-01 16:59:28 -07001343 InputEvent* consume() {
1344 if (mInputReceiver == nullptr) {
1345 return nullptr;
1346 }
1347 return mInputReceiver->consume();
1348 }
1349
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001350 MotionEvent* consumeMotion() {
1351 InputEvent* event = consume();
1352 if (event == nullptr) {
1353 ADD_FAILURE() << "Consume failed : no event";
1354 return nullptr;
1355 }
1356 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1357 ADD_FAILURE() << "Instead of motion event, got "
1358 << inputEventTypeToString(event->getType());
1359 return nullptr;
1360 }
1361 return static_cast<MotionEvent*>(event);
1362 }
1363
Arthur Hungb92218b2018-08-14 12:00:21 +08001364 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001365 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001366 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001367 return; // Can't receive events if the window does not have input channel
1368 }
1369 ASSERT_NE(nullptr, mInputReceiver)
1370 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001371 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001372 }
1373
chaviwaf87b3e2019-10-01 16:59:28 -07001374 sp<IBinder> getToken() { return mInfo.token; }
1375
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001376 const std::string& getName() { return mName; }
1377
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001378 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1379 mInfo.ownerPid = ownerPid;
1380 mInfo.ownerUid = ownerUid;
1381 }
1382
Prabir Pradhanedd96402022-02-15 01:46:16 -08001383 int32_t getPid() const { return mInfo.ownerPid; }
1384
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001385 void destroyReceiver() { mInputReceiver = nullptr; }
1386
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001387 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1388
chaviwd1c23182019-12-20 18:44:56 -08001389private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001390 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001391 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001392 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001393};
1394
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001395std::atomic<int32_t> FakeWindowHandle::sId{1};
1396
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001397static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001398 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 int32_t displayId = ADISPLAY_ID_NONE,
1400 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001401 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001402 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1403 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001404 KeyEvent event;
1405 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1406
1407 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001408 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001409 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1410 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001411
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001412 if (!allowKeyRepeat) {
1413 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1414 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001415 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001416 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001417}
1418
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001419static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001420 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001421 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1422}
1423
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001424// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1425// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1426// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001427static InputEventInjectionResult injectKeyDownNoRepeat(
1428 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001429 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1430 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1431 /* allowKeyRepeat */ false);
1432}
1433
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001434static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001435 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001436 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1437}
1438
Garfield Tandf26e862020-07-01 20:18:19 -07001439class PointerBuilder {
1440public:
1441 PointerBuilder(int32_t id, int32_t toolType) {
1442 mProperties.clear();
1443 mProperties.id = id;
1444 mProperties.toolType = toolType;
1445 mCoords.clear();
1446 }
1447
1448 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1449
1450 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1451
1452 PointerBuilder& axis(int32_t axis, float value) {
1453 mCoords.setAxisValue(axis, value);
1454 return *this;
1455 }
1456
1457 PointerProperties buildProperties() const { return mProperties; }
1458
1459 PointerCoords buildCoords() const { return mCoords; }
1460
1461private:
1462 PointerProperties mProperties;
1463 PointerCoords mCoords;
1464};
1465
1466class MotionEventBuilder {
1467public:
1468 MotionEventBuilder(int32_t action, int32_t source) {
1469 mAction = action;
1470 mSource = source;
1471 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1472 }
1473
1474 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1475 mEventTime = eventTime;
1476 return *this;
1477 }
1478
1479 MotionEventBuilder& displayId(int32_t displayId) {
1480 mDisplayId = displayId;
1481 return *this;
1482 }
1483
1484 MotionEventBuilder& actionButton(int32_t actionButton) {
1485 mActionButton = actionButton;
1486 return *this;
1487 }
1488
arthurhung6d4bed92021-03-17 11:59:33 +08001489 MotionEventBuilder& buttonState(int32_t buttonState) {
1490 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001491 return *this;
1492 }
1493
1494 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1495 mRawXCursorPosition = rawXCursorPosition;
1496 return *this;
1497 }
1498
1499 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1500 mRawYCursorPosition = rawYCursorPosition;
1501 return *this;
1502 }
1503
1504 MotionEventBuilder& pointer(PointerBuilder pointer) {
1505 mPointers.push_back(pointer);
1506 return *this;
1507 }
1508
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001509 MotionEventBuilder& addFlag(uint32_t flags) {
1510 mFlags |= flags;
1511 return *this;
1512 }
1513
Garfield Tandf26e862020-07-01 20:18:19 -07001514 MotionEvent build() {
1515 std::vector<PointerProperties> pointerProperties;
1516 std::vector<PointerCoords> pointerCoords;
1517 for (const PointerBuilder& pointer : mPointers) {
1518 pointerProperties.push_back(pointer.buildProperties());
1519 pointerCoords.push_back(pointer.buildCoords());
1520 }
1521
1522 // Set mouse cursor position for the most common cases to avoid boilerplate.
1523 if (mSource == AINPUT_SOURCE_MOUSE &&
1524 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1525 mPointers.size() == 1) {
1526 mRawXCursorPosition = pointerCoords[0].getX();
1527 mRawYCursorPosition = pointerCoords[0].getY();
1528 }
1529
1530 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001531 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001532 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001533 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001534 mButtonState, MotionClassification::NONE, identityTransform,
1535 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001536 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1537 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001538
1539 return event;
1540 }
1541
1542private:
1543 int32_t mAction;
1544 int32_t mSource;
1545 nsecs_t mEventTime;
1546 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1547 int32_t mActionButton{0};
1548 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001549 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001550 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1551 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1552
1553 std::vector<PointerBuilder> mPointers;
1554};
1555
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001557 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001558 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001559 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1560 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1561 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1562 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001563}
1564
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001566 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001567 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001568 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001569 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1570 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001572 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1573 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001574 MotionEvent event = MotionEventBuilder(action, source)
1575 .displayId(displayId)
1576 .eventTime(eventTime)
1577 .rawXCursorPosition(cursorPosition.x)
1578 .rawYCursorPosition(cursorPosition.y)
1579 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1580 .x(position.x)
1581 .y(position.y))
1582 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001583
1584 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001585 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1586 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001587}
1588
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001589static InputEventInjectionResult injectMotionDown(
1590 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1591 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001592 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001593}
1594
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001595static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001596 int32_t source, int32_t displayId,
1597 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001598 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001599}
1600
Jackal Guof9696682018-10-05 12:23:23 +08001601static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1602 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1603 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001604 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1605 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1606 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001607
1608 return args;
1609}
1610
chaviwd1c23182019-12-20 18:44:56 -08001611static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1612 const std::vector<PointF>& points) {
1613 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001614 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1615 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1616 }
1617
chaviwd1c23182019-12-20 18:44:56 -08001618 PointerProperties pointerProperties[pointerCount];
1619 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001620
chaviwd1c23182019-12-20 18:44:56 -08001621 for (size_t i = 0; i < pointerCount; i++) {
1622 pointerProperties[i].clear();
1623 pointerProperties[i].id = i;
1624 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001625
chaviwd1c23182019-12-20 18:44:56 -08001626 pointerCoords[i].clear();
1627 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1628 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1629 }
Jackal Guof9696682018-10-05 12:23:23 +08001630
1631 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1632 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001633 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001634 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1635 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001636 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1637 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001638 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1639 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001640
1641 return args;
1642}
1643
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001644static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1645 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1646}
1647
chaviwd1c23182019-12-20 18:44:56 -08001648static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1649 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1650}
1651
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001652static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1653 const PointerCaptureRequest& request) {
1654 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001655}
1656
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001657/**
1658 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1659 * broken channel.
1660 */
1661TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1662 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1663 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001664 sp<FakeWindowHandle>::make(application, mDispatcher,
1665 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001666
1667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1668
1669 // Window closes its channel, but the window remains.
1670 window->destroyReceiver();
1671 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1672}
1673
Arthur Hungb92218b2018-08-14 12:00:21 +08001674TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001675 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001676 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1677 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001678
Arthur Hung72d8dc32020-03-28 00:48:39 +00001679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1681 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001683
1684 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001685 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001686}
1687
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001688TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001690 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1691 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001692
1693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1694 // Inject a MotionEvent to an unknown display.
1695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1696 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1698
1699 // Window should receive motion event.
1700 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1701}
1702
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001703/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001704 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001705 * This test serves as a sanity check for the next test, where setInputWindows is
1706 * called twice.
1707 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001708TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001710 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1711 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001712 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001713
1714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001716 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1717 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001719
1720 // Window should receive motion event.
1721 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1722}
1723
1724/**
1725 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001726 */
1727TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001728 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001729 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1730 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001731 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001732
1733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001736 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1737 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001738 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001739
1740 // Window should receive motion event.
1741 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1742}
1743
Arthur Hungb92218b2018-08-14 12:00:21 +08001744// The foreground window should receive the first touch down event.
1745TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001746 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001747 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001748 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001749 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001750 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001751
Arthur Hung72d8dc32020-03-28 00:48:39 +00001752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001756
1757 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001758 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001759 windowSecond->assertNoEvents();
1760}
1761
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001762/**
1763 * Two windows: A top window, and a wallpaper behind the window.
1764 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1765 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001766 * 1. foregroundWindow <-- dup touch to wallpaper
1767 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001768 */
1769TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1771 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001772 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001773 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001774 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001775 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001776 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001777
1778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1781 {100, 200}))
1782 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1783
1784 // Both foreground window and its wallpaper should receive the touch down
1785 foregroundWindow->consumeMotionDown();
1786 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1787
1788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1789 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1790 ADISPLAY_ID_DEFAULT, {110, 200}))
1791 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1792
1793 foregroundWindow->consumeMotionMove();
1794 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1795
1796 // Now the foreground window goes away, but the wallpaper stays
1797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1798 foregroundWindow->consumeMotionCancel();
1799 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1800 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1801}
1802
1803/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001804 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1805 * with the following differences:
1806 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1807 * clean up the connection.
1808 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1809 * Ensure that there's no crash in the dispatcher.
1810 */
1811TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1812 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1813 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001814 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001815 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001816 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001817 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001818 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001819
1820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1823 {100, 200}))
1824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1825
1826 // Both foreground window and its wallpaper should receive the touch down
1827 foregroundWindow->consumeMotionDown();
1828 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1829
1830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1831 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1832 ADISPLAY_ID_DEFAULT, {110, 200}))
1833 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1834
1835 foregroundWindow->consumeMotionMove();
1836 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1837
1838 // Wallpaper closes its channel, but the window remains.
1839 wallpaperWindow->destroyReceiver();
1840 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1841
1842 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1843 // is no longer valid.
1844 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1845 foregroundWindow->consumeMotionCancel();
1846}
1847
Arthur Hungc539dbb2022-12-08 07:45:36 +00001848class ShouldSplitTouchFixture : public InputDispatcherTest,
1849 public ::testing::WithParamInterface<bool> {};
1850INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1851 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001852/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001853 * A single window that receives touch (on top), and a wallpaper window underneath it.
1854 * The top window gets a multitouch gesture.
1855 * Ensure that wallpaper gets the same gesture.
1856 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00001857TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001858 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00001859 sp<FakeWindowHandle> foregroundWindow =
1860 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1861 foregroundWindow->setDupTouchToWallpaper(true);
1862 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001863
1864 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001865 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001866 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001867
Arthur Hungc539dbb2022-12-08 07:45:36 +00001868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001869
1870 // Touch down on top window
1871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1872 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1873 {100, 100}))
1874 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1875
1876 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00001877 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001878 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1879
1880 // Second finger down on the top window
1881 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001882 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001883 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1884 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1885 .x(100)
1886 .y(100))
1887 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1888 .x(150)
1889 .y(150))
1890 .build();
1891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1892 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1893 InputEventInjectionSync::WAIT_FOR_RESULT))
1894 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1895
Arthur Hungc539dbb2022-12-08 07:45:36 +00001896 foregroundWindow->consumeMotionPointerDown(1 /* pointerIndex */);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001897 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1898 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00001899
1900 const MotionEvent secondFingerUpEvent =
1901 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1902 .displayId(ADISPLAY_ID_DEFAULT)
1903 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1904 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1905 .x(100)
1906 .y(100))
1907 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1908 .x(150)
1909 .y(150))
1910 .build();
1911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1912 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1913 InputEventInjectionSync::WAIT_FOR_RESULT))
1914 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1915 foregroundWindow->consumeMotionPointerUp(0);
1916 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1917
1918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1919 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1920 {100, 100}))
1921 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1922 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1923 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001924}
1925
1926/**
1927 * Two windows: a window on the left and window on the right.
1928 * A third window, wallpaper, is behind both windows, and spans both top windows.
1929 * The first touch down goes to the left window. A second pointer touches down on the right window.
1930 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1931 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1932 * ACTION_POINTER_DOWN(1).
1933 */
1934TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1936 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001937 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001938 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001939 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001940
1941 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001942 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001943 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001944 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001945
1946 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001947 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001948 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001949 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001950
1951 mDispatcher->setInputWindows(
1952 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1953
1954 // Touch down on left window
1955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1956 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1957 {100, 100}))
1958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1959
1960 // Both foreground window and its wallpaper should receive the touch down
1961 leftWindow->consumeMotionDown();
1962 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1963
1964 // Second finger down on the right window
1965 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001966 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001967 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1968 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1969 .x(100)
1970 .y(100))
1971 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1972 .x(300)
1973 .y(100))
1974 .build();
1975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1976 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1977 InputEventInjectionSync::WAIT_FOR_RESULT))
1978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1979
1980 leftWindow->consumeMotionMove();
1981 // Since the touch is split, right window gets ACTION_DOWN
1982 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1983 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1984 expectedWallpaperFlags);
1985
1986 // Now, leftWindow, which received the first finger, disappears.
1987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1988 leftWindow->consumeMotionCancel();
1989 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1990 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1991
1992 // The pointer that's still down on the right window moves, and goes to the right window only.
1993 // As far as the dispatcher's concerned though, both pointers are still present.
1994 const MotionEvent secondFingerMoveEvent =
1995 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1996 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1997 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1998 .x(100)
1999 .y(100))
2000 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2001 .x(310)
2002 .y(110))
2003 .build();
2004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2005 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2006 InputEventInjectionSync::WAIT_FOR_RESULT));
2007 rightWindow->consumeMotionMove();
2008
2009 leftWindow->assertNoEvents();
2010 rightWindow->assertNoEvents();
2011 wallpaperWindow->assertNoEvents();
2012}
2013
Arthur Hungc539dbb2022-12-08 07:45:36 +00002014/**
2015 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2016 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2017 * The right window should receive ACTION_DOWN.
2018 */
2019TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002020 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002021 sp<FakeWindowHandle> leftWindow =
2022 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2023 leftWindow->setFrame(Rect(0, 0, 200, 200));
2024 leftWindow->setDupTouchToWallpaper(true);
2025 leftWindow->setSlippery(true);
2026
2027 sp<FakeWindowHandle> rightWindow =
2028 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2029 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002030
2031 sp<FakeWindowHandle> wallpaperWindow =
2032 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2033 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002034
Arthur Hungc539dbb2022-12-08 07:45:36 +00002035 mDispatcher->setInputWindows(
2036 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002037
Arthur Hungc539dbb2022-12-08 07:45:36 +00002038 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2040 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002041 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002043
2044 // Both foreground window and its wallpaper should receive the touch down
2045 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002046 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2047
Arthur Hungc539dbb2022-12-08 07:45:36 +00002048 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002050 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2051 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2053
Arthur Hungc539dbb2022-12-08 07:45:36 +00002054 leftWindow->consumeMotionCancel();
2055 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2056 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002057}
2058
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002059/**
2060 * On the display, have a single window, and also an area where there's no window.
2061 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2062 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2063 */
2064TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2065 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2066 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002067 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002068
2069 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2070 NotifyMotionArgs args;
2071
2072 // Touch down on the empty space
2073 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2074
2075 mDispatcher->waitForIdle();
2076 window->assertNoEvents();
2077
2078 // Now touch down on the window with another pointer
2079 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2080 mDispatcher->waitForIdle();
2081 window->consumeMotionDown();
2082}
2083
2084/**
2085 * Same test as above, but instead of touching the empty space, the first touch goes to
2086 * non-touchable window.
2087 */
2088TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2089 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2090 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002091 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002092 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2093 window1->setTouchable(false);
2094 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002095 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002096 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2097
2098 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2099
2100 NotifyMotionArgs args;
2101 // Touch down on the non-touchable window
2102 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2103
2104 mDispatcher->waitForIdle();
2105 window1->assertNoEvents();
2106 window2->assertNoEvents();
2107
2108 // Now touch down on the window with another pointer
2109 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2110 mDispatcher->waitForIdle();
2111 window2->consumeMotionDown();
2112}
2113
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002114/**
2115 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2116 * to the event time of the first ACTION_DOWN sent to the particular window.
2117 */
2118TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2119 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2120 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002121 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002122 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2123 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002124 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002125 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2126
2127 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2128
2129 NotifyMotionArgs args;
2130 // Touch down on the first window
2131 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2132
2133 mDispatcher->waitForIdle();
2134 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002135 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002136 window2->assertNoEvents();
2137 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2138 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2139 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2140
2141 // Now touch down on the window with another pointer
2142 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2143 mDispatcher->waitForIdle();
2144 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002145 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002146 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2147 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2148 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2149 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2150
2151 // Now move the pointer on the second window
2152 mDispatcher->notifyMotion(
2153 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2154 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002155 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002156
2157 // Now add new touch down on the second window
2158 mDispatcher->notifyMotion(
2159 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2160 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002161 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002162
2163 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2164 window1->consumeMotionMove();
2165 window1->assertNoEvents();
2166
2167 // Now move the pointer on the first window
2168 mDispatcher->notifyMotion(
2169 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2170 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002171 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002172
2173 mDispatcher->notifyMotion(&(
2174 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2175 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002176 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002177}
2178
Garfield Tandf26e862020-07-01 20:18:19 -07002179TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002181 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002182 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002183 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002184 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002185 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002186 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002187
2188 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2189
2190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2191
2192 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002194 injectMotionEvent(mDispatcher,
2195 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2196 AINPUT_SOURCE_MOUSE)
2197 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2198 .x(900)
2199 .y(400))
2200 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002201 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002202
2203 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002204 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002205 injectMotionEvent(mDispatcher,
2206 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2207 AINPUT_SOURCE_MOUSE)
2208 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2209 .x(300)
2210 .y(400))
2211 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002212 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2213 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002214
2215 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002216 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002217 injectMotionEvent(mDispatcher,
2218 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2219 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2220 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2221 .x(300)
2222 .y(400))
2223 .build()));
2224 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2225
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002227 injectMotionEvent(mDispatcher,
2228 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2229 AINPUT_SOURCE_MOUSE)
2230 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2231 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2232 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2233 .x(300)
2234 .y(400))
2235 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002236 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002237
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002238 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002239 injectMotionEvent(mDispatcher,
2240 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2241 AINPUT_SOURCE_MOUSE)
2242 .buttonState(0)
2243 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2244 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2245 .x(300)
2246 .y(400))
2247 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002248 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002249
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002251 injectMotionEvent(mDispatcher,
2252 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2253 .buttonState(0)
2254 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2255 .x(300)
2256 .y(400))
2257 .build()));
2258 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2259
2260 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002262 injectMotionEvent(mDispatcher,
2263 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2264 AINPUT_SOURCE_MOUSE)
2265 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2266 .x(900)
2267 .y(400))
2268 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002269 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2270 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002271
2272 // No more events
2273 windowLeft->assertNoEvents();
2274 windowRight->assertNoEvents();
2275}
2276
2277TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
2278 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2279
2280 sp<FakeWindowHandle> spyWindow =
2281 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2282 spyWindow->setFrame(Rect(0, 0, 600, 800));
2283 spyWindow->setTrustedOverlay(true);
2284 spyWindow->setSpy(true);
2285 sp<FakeWindowHandle> window =
2286 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2287 window->setFrame(Rect(0, 0, 600, 800));
2288
2289 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2291
2292 // Send mouse cursor to the window
2293 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2294 injectMotionEvent(mDispatcher,
2295 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2296 AINPUT_SOURCE_MOUSE)
2297 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2298 .x(100)
2299 .y(100))
2300 .build()));
2301
2302 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2303 WithSource(AINPUT_SOURCE_MOUSE)));
2304 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2305 WithSource(AINPUT_SOURCE_MOUSE)));
2306
2307 window->assertNoEvents();
2308 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07002309}
2310
2311// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2312// directly in this test.
2313TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002314 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002315 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002316 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002317 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002318
2319 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2320
2321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2322
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002324 injectMotionEvent(mDispatcher,
2325 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2326 AINPUT_SOURCE_MOUSE)
2327 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2328 .x(300)
2329 .y(400))
2330 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002331 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002332 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002334 injectMotionEvent(mDispatcher,
2335 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2336 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2337 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2338 .x(300)
2339 .y(400))
2340 .build()));
2341 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2342
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002344 injectMotionEvent(mDispatcher,
2345 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2346 AINPUT_SOURCE_MOUSE)
2347 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2348 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2349 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2350 .x(300)
2351 .y(400))
2352 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002353 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002356 injectMotionEvent(mDispatcher,
2357 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2358 AINPUT_SOURCE_MOUSE)
2359 .buttonState(0)
2360 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2361 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2362 .x(300)
2363 .y(400))
2364 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002365 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002366
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002368 injectMotionEvent(mDispatcher,
2369 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2370 .buttonState(0)
2371 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2372 .x(300)
2373 .y(400))
2374 .build()));
2375 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2376
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002378 injectMotionEvent(mDispatcher,
2379 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2380 AINPUT_SOURCE_MOUSE)
2381 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2382 .x(300)
2383 .y(400))
2384 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002385 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
Garfield Tandf26e862020-07-01 20:18:19 -07002386}
2387
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002388/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002389 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
2390 * is generated.
2391 */
2392TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
2393 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2394 sp<FakeWindowHandle> window =
2395 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2396 window->setFrame(Rect(0, 0, 1200, 800));
2397
2398 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2399
2400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2401
2402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2403 injectMotionEvent(mDispatcher,
2404 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2405 AINPUT_SOURCE_MOUSE)
2406 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2407 .x(300)
2408 .y(400))
2409 .build()));
2410 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2411
2412 // Remove the window, but keep the channel.
2413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2414 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2415}
2416
2417/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002418 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002419 * The tap causes a HOVER_EXIT event to be generated because the current event
2420 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002421 */
2422TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2423 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2424 sp<FakeWindowHandle> window =
2425 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2426 window->setFrame(Rect(0, 0, 100, 100));
2427
2428 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2429
2430 // Inject a hover_move from mouse.
2431 NotifyMotionArgs motionArgs =
2432 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2433 ADISPLAY_ID_DEFAULT, {{50, 50}});
2434 motionArgs.xCursorPosition = 50;
2435 motionArgs.yCursorPosition = 50;
2436 mDispatcher->notifyMotion(&motionArgs);
2437 ASSERT_NO_FATAL_FAILURE(
2438 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2439 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002440
2441 // Tap on the window
2442 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2443 ADISPLAY_ID_DEFAULT, {{10, 10}});
2444 mDispatcher->notifyMotion(&motionArgs);
2445 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002446 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2447 WithSource(AINPUT_SOURCE_MOUSE))));
2448
2449 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002450 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2451 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2452
2453 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2454 ADISPLAY_ID_DEFAULT, {{10, 10}});
2455 mDispatcher->notifyMotion(&motionArgs);
2456 ASSERT_NO_FATAL_FAILURE(
2457 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2458 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2459}
2460
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002461TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2462 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2463 sp<FakeWindowHandle> windowDefaultDisplay =
2464 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2465 ADISPLAY_ID_DEFAULT);
2466 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2467 sp<FakeWindowHandle> windowSecondDisplay =
2468 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2469 SECOND_DISPLAY_ID);
2470 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2471
2472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2473 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2474
2475 // Set cursor position in window in default display and check that hover enter and move
2476 // events are generated.
2477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2478 injectMotionEvent(mDispatcher,
2479 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2480 AINPUT_SOURCE_MOUSE)
2481 .displayId(ADISPLAY_ID_DEFAULT)
2482 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2483 .x(300)
2484 .y(600))
2485 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002486 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002487
2488 // Remove all windows in secondary display and check that no event happens on window in
2489 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002490 mDispatcher->setInputWindows(
2491 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002492 windowDefaultDisplay->assertNoEvents();
2493
2494 // Move cursor position in window in default display and check that only hover move
2495 // event is generated and not hover enter event.
2496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2497 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2499 injectMotionEvent(mDispatcher,
2500 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2501 AINPUT_SOURCE_MOUSE)
2502 .displayId(ADISPLAY_ID_DEFAULT)
2503 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2504 .x(400)
2505 .y(700))
2506 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002507 windowDefaultDisplay->consumeMotionEvent(
2508 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2509 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002510 windowDefaultDisplay->assertNoEvents();
2511}
2512
Garfield Tan00f511d2019-06-12 16:55:40 -07002513TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002514 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002515
2516 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002517 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002518 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002519 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002520 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002521 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002522
2523 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2524
Arthur Hung72d8dc32020-03-28 00:48:39 +00002525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002526
2527 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2528 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002530 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002531 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002532 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002533 windowRight->assertNoEvents();
2534}
2535
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002536TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002538 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2539 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002540 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002541
Arthur Hung72d8dc32020-03-28 00:48:39 +00002542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002543 setFocusedWindow(window);
2544
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002545 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002546
2547 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2548 mDispatcher->notifyKey(&keyArgs);
2549
2550 // Window should receive key down event.
2551 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2552
2553 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2554 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002555 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002556 mDispatcher->notifyDeviceReset(&args);
2557 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2558 AKEY_EVENT_FLAG_CANCELED);
2559}
2560
2561TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002563 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2564 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002565
Arthur Hung72d8dc32020-03-28 00:48:39 +00002566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002567
2568 NotifyMotionArgs motionArgs =
2569 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2570 ADISPLAY_ID_DEFAULT);
2571 mDispatcher->notifyMotion(&motionArgs);
2572
2573 // Window should receive motion down event.
2574 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2575
2576 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2577 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002578 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002579 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08002580 window->consumeMotionEvent(
2581 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002582}
2583
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002584TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002586 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2587 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002588 window->setFocusable(true);
2589
2590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2591 setFocusedWindow(window);
2592
2593 window->consumeFocusEvent(true);
2594
2595 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2596 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2597 const nsecs_t injectTime = keyArgs.eventTime;
2598 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2599 mDispatcher->notifyKey(&keyArgs);
2600 // The dispatching time should be always greater than or equal to intercept key timeout.
2601 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2602 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2603 std::chrono::nanoseconds(interceptKeyTimeout).count());
2604}
2605
2606TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2607 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002608 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2609 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002610 window->setFocusable(true);
2611
2612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2613 setFocusedWindow(window);
2614
2615 window->consumeFocusEvent(true);
2616
2617 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2618 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2619 mFakePolicy->setInterceptKeyTimeout(150ms);
2620 mDispatcher->notifyKey(&keyDown);
2621 mDispatcher->notifyKey(&keyUp);
2622
2623 // Window should receive key event immediately when same key up.
2624 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2625 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2626}
2627
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002628/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002629 * Two windows. First is a regular window. Second does not overlap with the first, and has
2630 * WATCH_OUTSIDE_TOUCH.
2631 * Both windows are owned by the same UID.
2632 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
2633 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
2634 */
2635TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
2636 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2637 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2638 "First Window", ADISPLAY_ID_DEFAULT);
2639 window->setFrame(Rect{0, 0, 100, 100});
2640
2641 sp<FakeWindowHandle> outsideWindow =
2642 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2643 ADISPLAY_ID_DEFAULT);
2644 outsideWindow->setFrame(Rect{100, 100, 200, 200});
2645 outsideWindow->setWatchOutsideTouch(true);
2646 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
2647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
2648
2649 // Tap on first window.
2650 NotifyMotionArgs motionArgs =
2651 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2652 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
2653 mDispatcher->notifyMotion(&motionArgs);
2654 window->consumeMotionDown();
2655 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
2656 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
2657 outsideWindow->consumeMotionEvent(
2658 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
2659}
2660
2661/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002662 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2663 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2664 * ACTION_OUTSIDE event is sent per gesture.
2665 */
2666TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2667 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002669 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2670 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002671 window->setWatchOutsideTouch(true);
2672 window->setFrame(Rect{0, 0, 100, 100});
2673 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002674 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2675 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002676 secondWindow->setFrame(Rect{100, 100, 200, 200});
2677 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002678 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2679 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002680 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2682
2683 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2684 NotifyMotionArgs motionArgs =
2685 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2686 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2687 mDispatcher->notifyMotion(&motionArgs);
2688 window->assertNoEvents();
2689 secondWindow->assertNoEvents();
2690
2691 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2692 // Now, `window` should get ACTION_OUTSIDE.
2693 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2694 {PointF{-10, -10}, PointF{105, 105}});
2695 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002696 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
2697 window->consumeMotionEvent(
2698 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002699 secondWindow->consumeMotionDown();
2700 thirdWindow->assertNoEvents();
2701
2702 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2703 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2704 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2705 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2706 mDispatcher->notifyMotion(&motionArgs);
2707 window->assertNoEvents();
2708 secondWindow->consumeMotionMove();
2709 thirdWindow->consumeMotionDown();
2710}
2711
Prabir Pradhan814fe082022-07-22 20:22:18 +00002712TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2713 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002714 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2715 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002716 window->setFocusable(true);
2717
2718 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2719 setFocusedWindow(window);
2720
2721 window->consumeFocusEvent(true);
2722
2723 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2724 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2725 mDispatcher->notifyKey(&keyDown);
2726 mDispatcher->notifyKey(&keyUp);
2727
2728 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2729 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2730
2731 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2732 mDispatcher->onWindowInfosChanged({}, {});
2733
2734 window->consumeFocusEvent(false);
2735
2736 mDispatcher->notifyKey(&keyDown);
2737 mDispatcher->notifyKey(&keyUp);
2738 window->assertNoEvents();
2739}
2740
Arthur Hung96483742022-11-15 03:30:48 +00002741TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2742 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2743 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2744 "Fake Window", ADISPLAY_ID_DEFAULT);
2745 // Ensure window is non-split and have some transform.
2746 window->setPreventSplitting(true);
2747 window->setWindowOffset(20, 40);
2748 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2749
2750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2751 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2752 {50, 50}))
2753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2754 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2755
2756 const MotionEvent secondFingerDownEvent =
2757 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2758 .displayId(ADISPLAY_ID_DEFAULT)
2759 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2760 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2761 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2762 .x(-30)
2763 .y(-50))
2764 .build();
2765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2766 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2767 InputEventInjectionSync::WAIT_FOR_RESULT))
2768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2769
2770 const MotionEvent* event = window->consumeMotion();
2771 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2772 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2773 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2774 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2775 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2776}
2777
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002778/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002779 * Ensure the correct coordinate spaces are used by InputDispatcher.
2780 *
2781 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2782 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2783 * space.
2784 */
2785class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2786public:
2787 void SetUp() override {
2788 InputDispatcherTest::SetUp();
2789 mDisplayInfos.clear();
2790 mWindowInfos.clear();
2791 }
2792
2793 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2794 gui::DisplayInfo info;
2795 info.displayId = displayId;
2796 info.transform = transform;
2797 mDisplayInfos.push_back(std::move(info));
2798 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2799 }
2800
2801 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2802 mWindowInfos.push_back(*windowHandle->getInfo());
2803 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2804 }
2805
2806 // Set up a test scenario where the display has a scaled projection and there are two windows
2807 // on the display.
2808 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2809 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2810 // respectively.
2811 ui::Transform displayTransform;
2812 displayTransform.set(2, 0, 0, 4);
2813 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2814
2815 std::shared_ptr<FakeApplicationHandle> application =
2816 std::make_shared<FakeApplicationHandle>();
2817
2818 // Add two windows to the display. Their frames are represented in the display space.
2819 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002820 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2821 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002822 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2823 addWindow(firstWindow);
2824
2825 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002826 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2827 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002828 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2829 addWindow(secondWindow);
2830 return {std::move(firstWindow), std::move(secondWindow)};
2831 }
2832
2833private:
2834 std::vector<gui::DisplayInfo> mDisplayInfos;
2835 std::vector<gui::WindowInfo> mWindowInfos;
2836};
2837
2838TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2839 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2840 // Send down to the first window. The point is represented in the display space. The point is
2841 // selected so that if the hit test was done with the transform applied to it, then it would
2842 // end up in the incorrect window.
2843 NotifyMotionArgs downMotionArgs =
2844 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2845 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2846 mDispatcher->notifyMotion(&downMotionArgs);
2847
2848 firstWindow->consumeMotionDown();
2849 secondWindow->assertNoEvents();
2850}
2851
2852// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2853// the event should be treated as being in the logical display space.
2854TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2855 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2856 // Send down to the first window. The point is represented in the logical display space. The
2857 // point is selected so that if the hit test was done in logical display space, then it would
2858 // end up in the incorrect window.
2859 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2860 PointF{75 * 2, 55 * 4});
2861
2862 firstWindow->consumeMotionDown();
2863 secondWindow->assertNoEvents();
2864}
2865
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002866// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2867// event should be treated as being in the logical display space.
2868TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2869 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2870
2871 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2872 ui::Transform injectedEventTransform;
2873 injectedEventTransform.set(matrix);
2874 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2875 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2876
2877 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2878 .displayId(ADISPLAY_ID_DEFAULT)
2879 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2880 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2881 .x(untransformedPoint.x)
2882 .y(untransformedPoint.y))
2883 .build();
2884 event.transform(matrix);
2885
2886 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2887 InputEventInjectionSync::WAIT_FOR_RESULT);
2888
2889 firstWindow->consumeMotionDown();
2890 secondWindow->assertNoEvents();
2891}
2892
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002893TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2894 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2895
2896 // Send down to the second window.
2897 NotifyMotionArgs downMotionArgs =
2898 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2899 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2900 mDispatcher->notifyMotion(&downMotionArgs);
2901
2902 firstWindow->assertNoEvents();
2903 const MotionEvent* event = secondWindow->consumeMotion();
2904 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2905
2906 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2907 EXPECT_EQ(300, event->getRawX(0));
2908 EXPECT_EQ(880, event->getRawY(0));
2909
2910 // Ensure that the x and y values are in the window's coordinate space.
2911 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2912 // the logical display space. This will be the origin of the window space.
2913 EXPECT_EQ(100, event->getX(0));
2914 EXPECT_EQ(80, event->getY(0));
2915}
2916
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002917using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2918 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002919
2920class TransferTouchFixture : public InputDispatcherTest,
2921 public ::testing::WithParamInterface<TransferFunction> {};
2922
2923TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002924 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002925
2926 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002927 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002928 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2929 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002930 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002931 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002932 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2933 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002934 sp<FakeWindowHandle> wallpaper =
2935 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2936 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002937 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00002938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002939
2940 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002941 NotifyMotionArgs downMotionArgs =
2942 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2943 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002944 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002945
Svet Ganov5d3bc372020-01-26 23:11:07 -08002946 // Only the first window should get the down event
2947 firstWindow->consumeMotionDown();
2948 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002949 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002950
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002951 // Transfer touch to the second window
2952 TransferFunction f = GetParam();
2953 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2954 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002955 // The first window gets cancel and the second gets down
2956 firstWindow->consumeMotionCancel();
2957 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002958 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002959
2960 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002961 NotifyMotionArgs upMotionArgs =
2962 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2963 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002964 mDispatcher->notifyMotion(&upMotionArgs);
2965 // The first window gets no events and the second gets up
2966 firstWindow->assertNoEvents();
2967 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002968 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002969}
2970
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002971/**
2972 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2973 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2974 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2975 * natural to the user.
2976 * In this test, we are sending a pointer to both spy window and first window. We then try to
2977 * transfer touch to the second window. The dispatcher should identify the first window as the
2978 * one that should lose the gesture, and therefore the action should be to move the gesture from
2979 * the first window to the second.
2980 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2981 * the other API, as well.
2982 */
2983TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2985
2986 // Create a couple of windows + a spy window
2987 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002988 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002989 spyWindow->setTrustedOverlay(true);
2990 spyWindow->setSpy(true);
2991 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002992 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002993 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002994 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002995
2996 // Add the windows to the dispatcher
2997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2998
2999 // Send down to the first window
3000 NotifyMotionArgs downMotionArgs =
3001 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3002 ADISPLAY_ID_DEFAULT);
3003 mDispatcher->notifyMotion(&downMotionArgs);
3004 // Only the first window and spy should get the down event
3005 spyWindow->consumeMotionDown();
3006 firstWindow->consumeMotionDown();
3007
3008 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
3009 // if f === 'transferTouch'.
3010 TransferFunction f = GetParam();
3011 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3012 ASSERT_TRUE(success);
3013 // The first window gets cancel and the second gets down
3014 firstWindow->consumeMotionCancel();
3015 secondWindow->consumeMotionDown();
3016
3017 // Send up event to the second window
3018 NotifyMotionArgs upMotionArgs =
3019 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3020 ADISPLAY_ID_DEFAULT);
3021 mDispatcher->notifyMotion(&upMotionArgs);
3022 // The first window gets no events and the second+spy get up
3023 firstWindow->assertNoEvents();
3024 spyWindow->consumeMotionUp();
3025 secondWindow->consumeMotionUp();
3026}
3027
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003028TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003029 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003030
3031 PointF touchPoint = {10, 10};
3032
3033 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003034 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003035 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3036 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003037 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003038 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003039 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3040 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003041 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003042
3043 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003045
3046 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003047 NotifyMotionArgs downMotionArgs =
3048 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3049 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003050 mDispatcher->notifyMotion(&downMotionArgs);
3051 // Only the first window should get the down event
3052 firstWindow->consumeMotionDown();
3053 secondWindow->assertNoEvents();
3054
3055 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003056 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003057 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003058 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003059 mDispatcher->notifyMotion(&pointerDownMotionArgs);
3060 // Only the first window should get the pointer down event
3061 firstWindow->consumeMotionPointerDown(1);
3062 secondWindow->assertNoEvents();
3063
3064 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003065 TransferFunction f = GetParam();
3066 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3067 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003068 // The first window gets cancel and the second gets down and pointer down
3069 firstWindow->consumeMotionCancel();
3070 secondWindow->consumeMotionDown();
3071 secondWindow->consumeMotionPointerDown(1);
3072
3073 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003074 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003075 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003076 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003077 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3078 // The first window gets nothing and the second gets pointer up
3079 firstWindow->assertNoEvents();
3080 secondWindow->consumeMotionPointerUp(1);
3081
3082 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003083 NotifyMotionArgs upMotionArgs =
3084 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3085 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003086 mDispatcher->notifyMotion(&upMotionArgs);
3087 // The first window gets nothing and the second gets up
3088 firstWindow->assertNoEvents();
3089 secondWindow->consumeMotionUp();
3090}
3091
Arthur Hungc539dbb2022-12-08 07:45:36 +00003092TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
3093 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3094
3095 // Create a couple of windows
3096 sp<FakeWindowHandle> firstWindow =
3097 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3098 ADISPLAY_ID_DEFAULT);
3099 firstWindow->setDupTouchToWallpaper(true);
3100 sp<FakeWindowHandle> secondWindow =
3101 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3102 ADISPLAY_ID_DEFAULT);
3103 secondWindow->setDupTouchToWallpaper(true);
3104
3105 sp<FakeWindowHandle> wallpaper1 =
3106 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
3107 wallpaper1->setIsWallpaper(true);
3108
3109 sp<FakeWindowHandle> wallpaper2 =
3110 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
3111 wallpaper2->setIsWallpaper(true);
3112 // Add the windows to the dispatcher
3113 mDispatcher->setInputWindows(
3114 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
3115
3116 // Send down to the first window
3117 NotifyMotionArgs downMotionArgs =
3118 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3119 ADISPLAY_ID_DEFAULT);
3120 mDispatcher->notifyMotion(&downMotionArgs);
3121
3122 // Only the first window should get the down event
3123 firstWindow->consumeMotionDown();
3124 secondWindow->assertNoEvents();
3125 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3126 wallpaper2->assertNoEvents();
3127
3128 // Transfer touch focus to the second window
3129 TransferFunction f = GetParam();
3130 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3131 ASSERT_TRUE(success);
3132
3133 // The first window gets cancel and the second gets down
3134 firstWindow->consumeMotionCancel();
3135 secondWindow->consumeMotionDown();
3136 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3137 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3138
3139 // Send up event to the second window
3140 NotifyMotionArgs upMotionArgs =
3141 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3142 ADISPLAY_ID_DEFAULT);
3143 mDispatcher->notifyMotion(&upMotionArgs);
3144 // The first window gets no events and the second gets up
3145 firstWindow->assertNoEvents();
3146 secondWindow->consumeMotionUp();
3147 wallpaper1->assertNoEvents();
3148 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3149}
3150
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003151// For the cases of single pointer touch and two pointers non-split touch, the api's
3152// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
3153// for the case where there are multiple pointers split across several windows.
3154INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
3155 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003156 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3157 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003158 return dispatcher->transferTouch(destChannelToken,
3159 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003160 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003161 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3162 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003163 return dispatcher->transferTouchFocus(from, to,
3164 false /*isDragAndDrop*/);
3165 }));
3166
Svet Ganov5d3bc372020-01-26 23:11:07 -08003167TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003168 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003169
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003170 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003171 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3172 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003173 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003174
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003175 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003176 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3177 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003178 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003179
3180 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003182
3183 PointF pointInFirst = {300, 200};
3184 PointF pointInSecond = {300, 600};
3185
3186 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003187 NotifyMotionArgs firstDownMotionArgs =
3188 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3189 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003190 mDispatcher->notifyMotion(&firstDownMotionArgs);
3191 // Only the first window should get the down event
3192 firstWindow->consumeMotionDown();
3193 secondWindow->assertNoEvents();
3194
3195 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003196 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003197 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003198 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003199 mDispatcher->notifyMotion(&secondDownMotionArgs);
3200 // The first window gets a move and the second a down
3201 firstWindow->consumeMotionMove();
3202 secondWindow->consumeMotionDown();
3203
3204 // Transfer touch focus to the second window
3205 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
3206 // The first window gets cancel and the new gets pointer down (it already saw down)
3207 firstWindow->consumeMotionCancel();
3208 secondWindow->consumeMotionPointerDown(1);
3209
3210 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003211 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003212 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003213 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003214 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3215 // The first window gets nothing and the second gets pointer up
3216 firstWindow->assertNoEvents();
3217 secondWindow->consumeMotionPointerUp(1);
3218
3219 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003220 NotifyMotionArgs upMotionArgs =
3221 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3222 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003223 mDispatcher->notifyMotion(&upMotionArgs);
3224 // The first window gets nothing and the second gets up
3225 firstWindow->assertNoEvents();
3226 secondWindow->consumeMotionUp();
3227}
3228
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003229// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3230// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3231// touch is not supported, so the touch should continue on those windows and the transferred-to
3232// window should get nothing.
3233TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3234 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3235
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003236 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003237 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3238 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003239 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003240
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003241 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003242 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3243 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003244 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003245
3246 // Add the windows to the dispatcher
3247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3248
3249 PointF pointInFirst = {300, 200};
3250 PointF pointInSecond = {300, 600};
3251
3252 // Send down to the first window
3253 NotifyMotionArgs firstDownMotionArgs =
3254 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3255 ADISPLAY_ID_DEFAULT, {pointInFirst});
3256 mDispatcher->notifyMotion(&firstDownMotionArgs);
3257 // Only the first window should get the down event
3258 firstWindow->consumeMotionDown();
3259 secondWindow->assertNoEvents();
3260
3261 // Send down to the second window
3262 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003263 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003264 {pointInFirst, pointInSecond});
3265 mDispatcher->notifyMotion(&secondDownMotionArgs);
3266 // The first window gets a move and the second a down
3267 firstWindow->consumeMotionMove();
3268 secondWindow->consumeMotionDown();
3269
3270 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003271 const bool transferred =
3272 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003273 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3274 ASSERT_FALSE(transferred);
3275 firstWindow->assertNoEvents();
3276 secondWindow->assertNoEvents();
3277
3278 // The rest of the dispatch should proceed as normal
3279 // Send pointer up to the second window
3280 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003281 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003282 {pointInFirst, pointInSecond});
3283 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3284 // The first window gets MOVE and the second gets pointer up
3285 firstWindow->consumeMotionMove();
3286 secondWindow->consumeMotionUp();
3287
3288 // Send up event to the first window
3289 NotifyMotionArgs upMotionArgs =
3290 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3291 ADISPLAY_ID_DEFAULT);
3292 mDispatcher->notifyMotion(&upMotionArgs);
3293 // The first window gets nothing and the second gets up
3294 firstWindow->consumeMotionUp();
3295 secondWindow->assertNoEvents();
3296}
3297
Arthur Hungabbb9d82021-09-01 14:52:30 +00003298// This case will create two windows and one mirrored window on the default display and mirror
3299// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3300// the windows info of second display before default display.
3301TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3302 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3303 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003304 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003305 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003306 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003307 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003308 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003309
3310 sp<FakeWindowHandle> mirrorWindowInPrimary =
3311 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3312 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003313
3314 sp<FakeWindowHandle> firstWindowInSecondary =
3315 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3316 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003317
3318 sp<FakeWindowHandle> secondWindowInSecondary =
3319 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3320 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003321
3322 // Update window info, let it find window handle of second display first.
3323 mDispatcher->setInputWindows(
3324 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3325 {ADISPLAY_ID_DEFAULT,
3326 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3327
3328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3329 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3330 {50, 50}))
3331 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3332
3333 // Window should receive motion event.
3334 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3335
3336 // Transfer touch focus
3337 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3338 secondWindowInPrimary->getToken()));
3339 // The first window gets cancel.
3340 firstWindowInPrimary->consumeMotionCancel();
3341 secondWindowInPrimary->consumeMotionDown();
3342
3343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3344 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3345 ADISPLAY_ID_DEFAULT, {150, 50}))
3346 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3347 firstWindowInPrimary->assertNoEvents();
3348 secondWindowInPrimary->consumeMotionMove();
3349
3350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3351 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3352 {150, 50}))
3353 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3354 firstWindowInPrimary->assertNoEvents();
3355 secondWindowInPrimary->consumeMotionUp();
3356}
3357
3358// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3359// 'transferTouch' api.
3360TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3361 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3362 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003363 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003364 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003365 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003366 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003367 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003368
3369 sp<FakeWindowHandle> mirrorWindowInPrimary =
3370 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3371 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003372
3373 sp<FakeWindowHandle> firstWindowInSecondary =
3374 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3375 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003376
3377 sp<FakeWindowHandle> secondWindowInSecondary =
3378 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3379 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003380
3381 // Update window info, let it find window handle of second display first.
3382 mDispatcher->setInputWindows(
3383 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3384 {ADISPLAY_ID_DEFAULT,
3385 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3386
3387 // Touch on second display.
3388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3390 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3391
3392 // Window should receive motion event.
3393 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3394
3395 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003396 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003397
3398 // The first window gets cancel.
3399 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3400 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3401
3402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3403 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3404 SECOND_DISPLAY_ID, {150, 50}))
3405 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3406 firstWindowInPrimary->assertNoEvents();
3407 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3408
3409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3410 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3412 firstWindowInPrimary->assertNoEvents();
3413 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3414}
3415
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003416TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003417 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003418 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3419 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003420
Vishnu Nair47074b82020-08-14 11:54:47 -07003421 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003423 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003424
3425 window->consumeFocusEvent(true);
3426
3427 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3428 mDispatcher->notifyKey(&keyArgs);
3429
3430 // Window should receive key down event.
3431 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3432}
3433
3434TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003435 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003436 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3437 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003438
Arthur Hung72d8dc32020-03-28 00:48:39 +00003439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003440
3441 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3442 mDispatcher->notifyKey(&keyArgs);
3443 mDispatcher->waitForIdle();
3444
3445 window->assertNoEvents();
3446}
3447
3448// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3449TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003450 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003451 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3452 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003453
Arthur Hung72d8dc32020-03-28 00:48:39 +00003454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003455
3456 // Send key
3457 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3458 mDispatcher->notifyKey(&keyArgs);
3459 // Send motion
3460 NotifyMotionArgs motionArgs =
3461 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3462 ADISPLAY_ID_DEFAULT);
3463 mDispatcher->notifyMotion(&motionArgs);
3464
3465 // Window should receive only the motion event
3466 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3467 window->assertNoEvents(); // Key event or focus event will not be received
3468}
3469
arthurhungea3f4fc2020-12-21 23:18:53 +08003470TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3471 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3472
arthurhungea3f4fc2020-12-21 23:18:53 +08003473 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003474 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3475 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003476 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003477
arthurhungea3f4fc2020-12-21 23:18:53 +08003478 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003479 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3480 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003481 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003482
3483 // Add the windows to the dispatcher
3484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3485
3486 PointF pointInFirst = {300, 200};
3487 PointF pointInSecond = {300, 600};
3488
3489 // Send down to the first window
3490 NotifyMotionArgs firstDownMotionArgs =
3491 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3492 ADISPLAY_ID_DEFAULT, {pointInFirst});
3493 mDispatcher->notifyMotion(&firstDownMotionArgs);
3494 // Only the first window should get the down event
3495 firstWindow->consumeMotionDown();
3496 secondWindow->assertNoEvents();
3497
3498 // Send down to the second window
3499 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003500 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003501 {pointInFirst, pointInSecond});
3502 mDispatcher->notifyMotion(&secondDownMotionArgs);
3503 // The first window gets a move and the second a down
3504 firstWindow->consumeMotionMove();
3505 secondWindow->consumeMotionDown();
3506
3507 // Send pointer cancel to the second window
3508 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003509 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003510 {pointInFirst, pointInSecond});
3511 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3512 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3513 // The first window gets move and the second gets cancel.
3514 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3515 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3516
3517 // Send up event.
3518 NotifyMotionArgs upMotionArgs =
3519 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3520 ADISPLAY_ID_DEFAULT);
3521 mDispatcher->notifyMotion(&upMotionArgs);
3522 // The first window gets up and the second gets nothing.
3523 firstWindow->consumeMotionUp();
3524 secondWindow->assertNoEvents();
3525}
3526
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003527TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3528 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3529
3530 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003531 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3533 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3534 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3535 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3536
3537 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3538 window->assertNoEvents();
3539 mDispatcher->waitForIdle();
3540}
3541
chaviwd1c23182019-12-20 18:44:56 -08003542class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003543public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003544 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003545 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003546 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003547 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003548 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003549 }
3550
chaviwd1c23182019-12-20 18:44:56 -08003551 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3552
3553 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3554 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3555 expectedDisplayId, expectedFlags);
3556 }
3557
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003558 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3559
3560 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3561
chaviwd1c23182019-12-20 18:44:56 -08003562 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3563 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3564 expectedDisplayId, expectedFlags);
3565 }
3566
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003567 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3568 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3569 expectedDisplayId, expectedFlags);
3570 }
3571
chaviwd1c23182019-12-20 18:44:56 -08003572 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3573 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3574 expectedDisplayId, expectedFlags);
3575 }
3576
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003577 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003578 mInputReceiver->consumeMotionEvent(
3579 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3580 WithDisplayId(expectedDisplayId),
3581 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003582 }
3583
Arthur Hungfbfa5722021-11-16 02:45:54 +00003584 void consumeMotionPointerDown(int32_t pointerIdx) {
3585 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3586 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3587 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3588 0 /*expectedFlags*/);
3589 }
3590
Evan Rosky84f07f02021-04-16 10:42:42 -07003591 MotionEvent* consumeMotion() {
3592 InputEvent* event = mInputReceiver->consume();
3593 if (!event) {
3594 ADD_FAILURE() << "No event was produced";
3595 return nullptr;
3596 }
3597 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3598 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3599 return nullptr;
3600 }
3601 return static_cast<MotionEvent*>(event);
3602 }
3603
chaviwd1c23182019-12-20 18:44:56 -08003604 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3605
3606private:
3607 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003608};
3609
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003610using InputDispatcherMonitorTest = InputDispatcherTest;
3611
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003612/**
3613 * Two entities that receive touch: A window, and a global monitor.
3614 * The touch goes to the window, and then the window disappears.
3615 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3616 * for the monitor, as well.
3617 * 1. foregroundWindow
3618 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3619 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003620TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3622 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003623 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003624
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003625 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003626
3627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3630 {100, 200}))
3631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3632
3633 // Both the foreground window and the global monitor should receive the touch down
3634 window->consumeMotionDown();
3635 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3636
3637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3638 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3639 ADISPLAY_ID_DEFAULT, {110, 200}))
3640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3641
3642 window->consumeMotionMove();
3643 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3644
3645 // Now the foreground window goes away
3646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3647 window->consumeMotionCancel();
3648 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3649
3650 // If more events come in, there will be no more foreground window to send them to. This will
3651 // cause a cancel for the monitor, as well.
3652 ASSERT_EQ(InputEventInjectionResult::FAILED,
3653 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3654 ADISPLAY_ID_DEFAULT, {120, 200}))
3655 << "Injection should fail because the window was removed";
3656 window->assertNoEvents();
3657 // Global monitor now gets the cancel
3658 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3659}
3660
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003661TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003662 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003663 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3664 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003666
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003667 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003668
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003670 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003671 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003672 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003673 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003674}
3675
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003676TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3677 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003678
Chris Yea209fde2020-07-22 13:54:51 -07003679 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003680 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3681 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003683
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003685 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003687 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003688 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003689
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003690 // Pilfer pointers from the monitor.
3691 // This should not do anything and the window should continue to receive events.
3692 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003693
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003695 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3696 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003698
3699 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3700 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003701}
3702
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003703TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003704 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003705 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3706 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3708 window->setWindowOffset(20, 40);
3709 window->setWindowTransform(0, 1, -1, 0);
3710
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003711 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003712
3713 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3714 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3715 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3716 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3717 MotionEvent* event = monitor.consumeMotion();
3718 // Even though window has transform, gesture monitor must not.
3719 ASSERT_EQ(ui::Transform(), event->getTransform());
3720}
3721
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003722TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003723 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003724 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003725
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003726 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003727 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003728 << "Injection should fail if there is a monitor, but no touchable window";
3729 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003730}
3731
chaviw81e2bb92019-12-18 15:03:51 -08003732TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003733 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003734 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3735 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003736
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003738
3739 NotifyMotionArgs motionArgs =
3740 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3741 ADISPLAY_ID_DEFAULT);
3742
3743 mDispatcher->notifyMotion(&motionArgs);
3744 // Window should receive motion down event.
3745 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3746
3747 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003748 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003749 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3750 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3751 motionArgs.pointerCoords[0].getX() - 10);
3752
3753 mDispatcher->notifyMotion(&motionArgs);
3754 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3755 0 /*expectedFlags*/);
3756}
3757
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003758/**
3759 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3760 * the device default right away. In the test scenario, we check both the default value,
3761 * and the action of enabling / disabling.
3762 */
3763TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003764 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003765 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3766 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003767 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003768
3769 // Set focused application.
3770 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003771 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003772
3773 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003775 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003776 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3777
3778 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003779 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003781 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3782
3783 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003784 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003785 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003786 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003787 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003789 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003790 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3791
3792 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003793 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003795 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3796
3797 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003798 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003799 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003800 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003801 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003803 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003804 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3805
3806 window->assertNoEvents();
3807}
3808
Gang Wange9087892020-01-07 12:17:14 -05003809TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003811 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3812 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003813
3814 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003815 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003816
Arthur Hung72d8dc32020-03-28 00:48:39 +00003817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003818 setFocusedWindow(window);
3819
Gang Wange9087892020-01-07 12:17:14 -05003820 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3821
3822 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3823 mDispatcher->notifyKey(&keyArgs);
3824
3825 InputEvent* event = window->consume();
3826 ASSERT_NE(event, nullptr);
3827
3828 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3829 ASSERT_NE(verified, nullptr);
3830 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3831
3832 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3833 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3834 ASSERT_EQ(keyArgs.source, verified->source);
3835 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3836
3837 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3838
3839 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003840 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003841 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003842 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3843 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3844 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3845 ASSERT_EQ(0, verifiedKey.repeatCount);
3846}
3847
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003848TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003849 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003850 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3851 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003852
3853 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3854
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003855 ui::Transform transform;
3856 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3857
3858 gui::DisplayInfo displayInfo;
3859 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3860 displayInfo.transform = transform;
3861
3862 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003863
3864 NotifyMotionArgs motionArgs =
3865 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3866 ADISPLAY_ID_DEFAULT);
3867 mDispatcher->notifyMotion(&motionArgs);
3868
3869 InputEvent* event = window->consume();
3870 ASSERT_NE(event, nullptr);
3871
3872 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3873 ASSERT_NE(verified, nullptr);
3874 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3875
3876 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3877 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3878 EXPECT_EQ(motionArgs.source, verified->source);
3879 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3880
3881 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3882
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003883 const vec2 rawXY =
3884 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3885 motionArgs.pointerCoords[0].getXYValue());
3886 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3887 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003888 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003889 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003890 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003891 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3892 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3893}
3894
chaviw09c8d2d2020-08-24 15:48:26 -07003895/**
3896 * Ensure that separate calls to sign the same data are generating the same key.
3897 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3898 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3899 * tests.
3900 */
3901TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3902 KeyEvent event = getTestKeyEvent();
3903 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3904
3905 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3906 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3907 ASSERT_EQ(hmac1, hmac2);
3908}
3909
3910/**
3911 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3912 */
3913TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3914 KeyEvent event = getTestKeyEvent();
3915 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3916 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3917
3918 verifiedEvent.deviceId += 1;
3919 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3920
3921 verifiedEvent.source += 1;
3922 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3923
3924 verifiedEvent.eventTimeNanos += 1;
3925 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3926
3927 verifiedEvent.displayId += 1;
3928 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3929
3930 verifiedEvent.action += 1;
3931 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3932
3933 verifiedEvent.downTimeNanos += 1;
3934 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3935
3936 verifiedEvent.flags += 1;
3937 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3938
3939 verifiedEvent.keyCode += 1;
3940 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3941
3942 verifiedEvent.scanCode += 1;
3943 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3944
3945 verifiedEvent.metaState += 1;
3946 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3947
3948 verifiedEvent.repeatCount += 1;
3949 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3950}
3951
Vishnu Nair958da932020-08-21 17:12:37 -07003952TEST_F(InputDispatcherTest, SetFocusedWindow) {
3953 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3954 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003955 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003956 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003957 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003958 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3959
3960 // Top window is also focusable but is not granted focus.
3961 windowTop->setFocusable(true);
3962 windowSecond->setFocusable(true);
3963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3964 setFocusedWindow(windowSecond);
3965
3966 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3968 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003969
3970 // Focused window should receive event.
3971 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3972 windowTop->assertNoEvents();
3973}
3974
3975TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3976 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3977 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003978 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003979 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3980
3981 window->setFocusable(true);
3982 // Release channel for window is no longer valid.
3983 window->releaseChannel();
3984 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3985 setFocusedWindow(window);
3986
3987 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003988 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3989 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003990
3991 // window channel is invalid, so it should not receive any input event.
3992 window->assertNoEvents();
3993}
3994
3995TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3997 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003998 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003999 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07004000 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4001
Vishnu Nair958da932020-08-21 17:12:37 -07004002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4003 setFocusedWindow(window);
4004
4005 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004006 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4007 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004008
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004009 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07004010 window->assertNoEvents();
4011}
4012
4013TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
4014 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4015 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004016 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004017 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004018 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004019 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4020
4021 windowTop->setFocusable(true);
4022 windowSecond->setFocusable(true);
4023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4024 setFocusedWindow(windowTop);
4025 windowTop->consumeFocusEvent(true);
4026
4027 setFocusedWindow(windowSecond, windowTop);
4028 windowSecond->consumeFocusEvent(true);
4029 windowTop->consumeFocusEvent(false);
4030
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4032 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004033
4034 // Focused window should receive event.
4035 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4036}
4037
4038TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
4039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4040 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004041 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004042 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004043 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004044 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4045
4046 windowTop->setFocusable(true);
4047 windowSecond->setFocusable(true);
4048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4049 setFocusedWindow(windowSecond, windowTop);
4050
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004051 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4052 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004053
4054 // Event should be dropped.
4055 windowTop->assertNoEvents();
4056 windowSecond->assertNoEvents();
4057}
4058
4059TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
4060 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4061 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004062 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004063 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004064 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
4065 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004066 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4067
4068 window->setFocusable(true);
4069 previousFocusedWindow->setFocusable(true);
4070 window->setVisible(false);
4071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
4072 setFocusedWindow(previousFocusedWindow);
4073 previousFocusedWindow->consumeFocusEvent(true);
4074
4075 // Requesting focus on invisible window takes focus from currently focused window.
4076 setFocusedWindow(window);
4077 previousFocusedWindow->consumeFocusEvent(false);
4078
4079 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004080 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004081 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004082 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004083
4084 // Window does not get focus event or key down.
4085 window->assertNoEvents();
4086
4087 // Window becomes visible.
4088 window->setVisible(true);
4089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4090
4091 // Window receives focus event.
4092 window->consumeFocusEvent(true);
4093 // Focused window receives key down.
4094 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4095}
4096
Vishnu Nair599f1412021-06-21 10:39:58 -07004097TEST_F(InputDispatcherTest, DisplayRemoved) {
4098 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4099 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004100 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07004101 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4102
4103 // window is granted focus.
4104 window->setFocusable(true);
4105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4106 setFocusedWindow(window);
4107 window->consumeFocusEvent(true);
4108
4109 // When a display is removed window loses focus.
4110 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
4111 window->consumeFocusEvent(false);
4112}
4113
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004114/**
4115 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
4116 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
4117 * of the 'slipperyEnterWindow'.
4118 *
4119 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
4120 * a way so that the touched location is no longer covered by the top window.
4121 *
4122 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
4123 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
4124 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
4125 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
4126 * with ACTION_DOWN).
4127 * Thus, the touch has been transferred from the top window into the bottom window, because the top
4128 * window moved itself away from the touched location and had Flag::SLIPPERY.
4129 *
4130 * Even though the top window moved away from the touched location, it is still obscuring the bottom
4131 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
4132 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
4133 *
4134 * In this test, we ensure that the event received by the bottom window has
4135 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
4136 */
4137TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004138 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
4139 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004140
4141 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4142 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4143
4144 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004145 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004146 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004147 // Make sure this one overlaps the bottom window
4148 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
4149 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
4150 // one. Windows with the same owner are not considered to be occluding each other.
4151 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
4152
4153 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004154 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004155 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
4156
4157 mDispatcher->setInputWindows(
4158 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4159
4160 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
4161 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4162 ADISPLAY_ID_DEFAULT, {{50, 50}});
4163 mDispatcher->notifyMotion(&args);
4164 slipperyExitWindow->consumeMotionDown();
4165 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
4166 mDispatcher->setInputWindows(
4167 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4168
4169 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4170 ADISPLAY_ID_DEFAULT, {{51, 51}});
4171 mDispatcher->notifyMotion(&args);
4172
4173 slipperyExitWindow->consumeMotionCancel();
4174
4175 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
4176 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
4177}
4178
Garfield Tan1c7bc862020-01-28 13:24:04 -08004179class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
4180protected:
4181 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
4182 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
4183
Chris Yea209fde2020-07-22 13:54:51 -07004184 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004185 sp<FakeWindowHandle> mWindow;
4186
4187 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004188 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08004189 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004190 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004191 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
4192 ASSERT_EQ(OK, mDispatcher->start());
4193
4194 setUpWindow();
4195 }
4196
4197 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07004198 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004199 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004200
Vishnu Nair47074b82020-08-14 11:54:47 -07004201 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004203 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004204 mWindow->consumeFocusEvent(true);
4205 }
4206
Chris Ye2ad95392020-09-01 13:44:44 -07004207 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004208 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004209 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004210 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
4211 mDispatcher->notifyKey(&keyArgs);
4212
4213 // Window should receive key down event.
4214 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4215 }
4216
4217 void expectKeyRepeatOnce(int32_t repeatCount) {
4218 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
4219 InputEvent* repeatEvent = mWindow->consume();
4220 ASSERT_NE(nullptr, repeatEvent);
4221
4222 uint32_t eventType = repeatEvent->getType();
4223 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4224
4225 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4226 uint32_t eventAction = repeatKeyEvent->getAction();
4227 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4228 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4229 }
4230
Chris Ye2ad95392020-09-01 13:44:44 -07004231 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004232 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004233 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004234 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4235 mDispatcher->notifyKey(&keyArgs);
4236
4237 // Window should receive key down event.
4238 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
4239 0 /*expectedFlags*/);
4240 }
4241};
4242
4243TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07004244 sendAndConsumeKeyDown(1 /* deviceId */);
4245 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4246 expectKeyRepeatOnce(repeatCount);
4247 }
4248}
4249
4250TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
4251 sendAndConsumeKeyDown(1 /* deviceId */);
4252 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4253 expectKeyRepeatOnce(repeatCount);
4254 }
4255 sendAndConsumeKeyDown(2 /* deviceId */);
4256 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004257 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4258 expectKeyRepeatOnce(repeatCount);
4259 }
4260}
4261
4262TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07004263 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004264 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07004265 sendAndConsumeKeyUp(1 /* deviceId */);
4266 mWindow->assertNoEvents();
4267}
4268
4269TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
4270 sendAndConsumeKeyDown(1 /* deviceId */);
4271 expectKeyRepeatOnce(1 /*repeatCount*/);
4272 sendAndConsumeKeyDown(2 /* deviceId */);
4273 expectKeyRepeatOnce(1 /*repeatCount*/);
4274 // Stale key up from device 1.
4275 sendAndConsumeKeyUp(1 /* deviceId */);
4276 // Device 2 is still down, keep repeating
4277 expectKeyRepeatOnce(2 /*repeatCount*/);
4278 expectKeyRepeatOnce(3 /*repeatCount*/);
4279 // Device 2 key up
4280 sendAndConsumeKeyUp(2 /* deviceId */);
4281 mWindow->assertNoEvents();
4282}
4283
4284TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
4285 sendAndConsumeKeyDown(1 /* deviceId */);
4286 expectKeyRepeatOnce(1 /*repeatCount*/);
4287 sendAndConsumeKeyDown(2 /* deviceId */);
4288 expectKeyRepeatOnce(1 /*repeatCount*/);
4289 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
4290 sendAndConsumeKeyUp(2 /* deviceId */);
4291 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004292 mWindow->assertNoEvents();
4293}
4294
liushenxiang42232912021-05-21 20:24:09 +08004295TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4296 sendAndConsumeKeyDown(DEVICE_ID);
4297 expectKeyRepeatOnce(1 /*repeatCount*/);
4298 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
4299 mDispatcher->notifyDeviceReset(&args);
4300 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4301 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4302 mWindow->assertNoEvents();
4303}
4304
Garfield Tan1c7bc862020-01-28 13:24:04 -08004305TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004306 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004307 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4308 InputEvent* repeatEvent = mWindow->consume();
4309 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4310 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4311 IdGenerator::getSource(repeatEvent->getId()));
4312 }
4313}
4314
4315TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004316 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004317
4318 std::unordered_set<int32_t> idSet;
4319 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4320 InputEvent* repeatEvent = mWindow->consume();
4321 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4322 int32_t id = repeatEvent->getId();
4323 EXPECT_EQ(idSet.end(), idSet.find(id));
4324 idSet.insert(id);
4325 }
4326}
4327
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004328/* Test InputDispatcher for MultiDisplay */
4329class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4330public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004331 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004332 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004333
Chris Yea209fde2020-07-22 13:54:51 -07004334 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004335 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004336 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004337
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004338 // Set focus window for primary display, but focused display would be second one.
4339 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004340 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004342 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004343 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004344
Chris Yea209fde2020-07-22 13:54:51 -07004345 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004346 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004347 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004348 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004349 // Set focus display to second one.
4350 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4351 // Set focus window for second display.
4352 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004353 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004354 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004355 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004356 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004357 }
4358
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004359 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004360 InputDispatcherTest::TearDown();
4361
Chris Yea209fde2020-07-22 13:54:51 -07004362 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004363 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004364 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004365 windowInSecondary.clear();
4366 }
4367
4368protected:
Chris Yea209fde2020-07-22 13:54:51 -07004369 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004370 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004371 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004372 sp<FakeWindowHandle> windowInSecondary;
4373};
4374
4375TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4376 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4378 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4379 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004380 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004381 windowInSecondary->assertNoEvents();
4382
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004383 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4385 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4386 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004387 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004388 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004389}
4390
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004391TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004392 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4394 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004396 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004397 windowInSecondary->assertNoEvents();
4398
4399 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004402 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004403 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004404
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004405 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004406 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004407
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004408 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004409 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4410 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004411
4412 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004413 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004415 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004416 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004417 windowInSecondary->assertNoEvents();
4418}
4419
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004420// Test per-display input monitors for motion event.
4421TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004422 FakeMonitorReceiver monitorInPrimary =
4423 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4424 FakeMonitorReceiver monitorInSecondary =
4425 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004426
4427 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4429 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4430 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004431 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004432 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004433 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004434 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004435
4436 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4438 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4439 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004440 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004441 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004442 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004443 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004444
4445 // Test inject a non-pointer motion event.
4446 // If specific a display, it will dispatch to the focused window of particular display,
4447 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004451 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004452 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004453 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004454 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004455}
4456
4457// Test per-display input monitors for key event.
4458TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004459 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004460 FakeMonitorReceiver monitorInPrimary =
4461 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4462 FakeMonitorReceiver monitorInSecondary =
4463 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004464
4465 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4467 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004468 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004469 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004470 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004471 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004472}
4473
Vishnu Nair958da932020-08-21 17:12:37 -07004474TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4475 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004476 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004477 secondWindowInPrimary->setFocusable(true);
4478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4479 setFocusedWindow(secondWindowInPrimary);
4480 windowInPrimary->consumeFocusEvent(false);
4481 secondWindowInPrimary->consumeFocusEvent(true);
4482
4483 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4485 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004486 windowInPrimary->assertNoEvents();
4487 windowInSecondary->assertNoEvents();
4488 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4489}
4490
Arthur Hungdfd528e2021-12-08 13:23:04 +00004491TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4492 FakeMonitorReceiver monitorInPrimary =
4493 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4494 FakeMonitorReceiver monitorInSecondary =
4495 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4496
4497 // Test touch down on primary display.
4498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4499 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4500 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4501 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4502 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4503
4504 // Test touch down on second display.
4505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4506 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4508 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4509 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4510
4511 // Trigger cancel touch.
4512 mDispatcher->cancelCurrentTouch();
4513 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4514 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4515 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4516 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4517
4518 // Test inject a move motion event, no window/monitor should receive the event.
4519 ASSERT_EQ(InputEventInjectionResult::FAILED,
4520 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4521 ADISPLAY_ID_DEFAULT, {110, 200}))
4522 << "Inject motion event should return InputEventInjectionResult::FAILED";
4523 windowInPrimary->assertNoEvents();
4524 monitorInPrimary.assertNoEvents();
4525
4526 ASSERT_EQ(InputEventInjectionResult::FAILED,
4527 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4528 SECOND_DISPLAY_ID, {110, 200}))
4529 << "Inject motion event should return InputEventInjectionResult::FAILED";
4530 windowInSecondary->assertNoEvents();
4531 monitorInSecondary.assertNoEvents();
4532}
4533
Jackal Guof9696682018-10-05 12:23:23 +08004534class InputFilterTest : public InputDispatcherTest {
4535protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004536 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4537 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004538 NotifyMotionArgs motionArgs;
4539
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004540 motionArgs =
4541 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004542 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004543 motionArgs =
4544 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004545 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004546 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004547 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004548 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4549 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004550 } else {
4551 mFakePolicy->assertFilterInputEventWasNotCalled();
4552 }
4553 }
4554
4555 void testNotifyKey(bool expectToBeFiltered) {
4556 NotifyKeyArgs keyArgs;
4557
4558 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4559 mDispatcher->notifyKey(&keyArgs);
4560 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4561 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004562 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004563
4564 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004565 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004566 } else {
4567 mFakePolicy->assertFilterInputEventWasNotCalled();
4568 }
4569 }
4570};
4571
4572// Test InputFilter for MotionEvent
4573TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4574 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4575 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4576 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4577
4578 // Enable InputFilter
4579 mDispatcher->setInputFilterEnabled(true);
4580 // Test touch on both primary and second display, and check if both events are filtered.
4581 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4582 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4583
4584 // Disable InputFilter
4585 mDispatcher->setInputFilterEnabled(false);
4586 // Test touch on both primary and second display, and check if both events aren't filtered.
4587 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4588 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4589}
4590
4591// Test InputFilter for KeyEvent
4592TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4593 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4594 testNotifyKey(/*expectToBeFiltered*/ false);
4595
4596 // Enable InputFilter
4597 mDispatcher->setInputFilterEnabled(true);
4598 // Send a key event, and check if it is filtered.
4599 testNotifyKey(/*expectToBeFiltered*/ true);
4600
4601 // Disable InputFilter
4602 mDispatcher->setInputFilterEnabled(false);
4603 // Send a key event, and check if it isn't filtered.
4604 testNotifyKey(/*expectToBeFiltered*/ false);
4605}
4606
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004607// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4608// logical display coordinate space.
4609TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4610 ui::Transform firstDisplayTransform;
4611 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4612 ui::Transform secondDisplayTransform;
4613 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4614
4615 std::vector<gui::DisplayInfo> displayInfos(2);
4616 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4617 displayInfos[0].transform = firstDisplayTransform;
4618 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4619 displayInfos[1].transform = secondDisplayTransform;
4620
4621 mDispatcher->onWindowInfosChanged({}, displayInfos);
4622
4623 // Enable InputFilter
4624 mDispatcher->setInputFilterEnabled(true);
4625
4626 // Ensure the correct transforms are used for the displays.
4627 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4628 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4629}
4630
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004631class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4632protected:
4633 virtual void SetUp() override {
4634 InputDispatcherTest::SetUp();
4635
4636 /**
4637 * We don't need to enable input filter to test the injected event policy, but we enabled it
4638 * here to make the tests more realistic, since this policy only matters when inputfilter is
4639 * on.
4640 */
4641 mDispatcher->setInputFilterEnabled(true);
4642
4643 std::shared_ptr<InputApplicationHandle> application =
4644 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004645 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4646 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004647
4648 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4649 mWindow->setFocusable(true);
4650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4651 setFocusedWindow(mWindow);
4652 mWindow->consumeFocusEvent(true);
4653 }
4654
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004655 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4656 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004657 KeyEvent event;
4658
4659 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4660 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4661 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4662 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4663 const int32_t additionalPolicyFlags =
4664 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004666 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004667 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4668 policyFlags | additionalPolicyFlags));
4669
4670 InputEvent* received = mWindow->consume();
4671 ASSERT_NE(nullptr, received);
4672 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004673 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4674 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4675 ASSERT_EQ(flags, keyEvent.getFlags());
4676 }
4677
4678 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4679 int32_t flags) {
4680 MotionEvent event;
4681 PointerProperties pointerProperties[1];
4682 PointerCoords pointerCoords[1];
4683 pointerProperties[0].clear();
4684 pointerProperties[0].id = 0;
4685 pointerCoords[0].clear();
4686 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4687 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4688
4689 ui::Transform identityTransform;
4690 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4691 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4692 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4693 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4694 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004695 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004696 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004697 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4698
4699 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004701 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004702 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4703 policyFlags | additionalPolicyFlags));
4704
4705 InputEvent* received = mWindow->consume();
4706 ASSERT_NE(nullptr, received);
4707 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4708 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4709 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4710 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004711 }
4712
4713private:
4714 sp<FakeWindowHandle> mWindow;
4715};
4716
4717TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004718 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4719 // filter. Without it, the event will no different from a regularly injected event, and the
4720 // injected device id will be overwritten.
4721 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4722 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004723}
4724
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004725TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004727 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4728 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4729}
4730
4731TEST_F(InputFilterInjectionPolicyTest,
4732 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4733 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4734 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4735 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004736}
4737
4738TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4739 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004740 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004741}
4742
chaviwfd6d3512019-03-25 13:23:49 -07004743class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004744 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004745 InputDispatcherTest::SetUp();
4746
Chris Yea209fde2020-07-22 13:54:51 -07004747 std::shared_ptr<FakeApplicationHandle> application =
4748 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004749 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004750 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004751 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004752
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004753 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004754 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004755 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004756
4757 // Set focused application.
4758 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004759 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004760
4761 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004763 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004764 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004765 }
4766
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004767 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004768 InputDispatcherTest::TearDown();
4769
4770 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004771 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004772 }
4773
4774protected:
4775 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004776 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004777 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004778};
4779
4780// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4781// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4782// the onPointerDownOutsideFocus callback.
4783TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004785 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4786 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004788 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004789
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004790 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004791 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4792}
4793
4794// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4795// DOWN on the window that doesn't have focus. Ensure no window received the
4796// onPointerDownOutsideFocus callback.
4797TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004799 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004801 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004802
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004803 ASSERT_TRUE(mDispatcher->waitForIdle());
4804 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004805}
4806
4807// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4808// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4809TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4811 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004812 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004813 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004814
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004815 ASSERT_TRUE(mDispatcher->waitForIdle());
4816 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004817}
4818
4819// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4820// DOWN on the window that already has focus. Ensure no window received the
4821// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004822TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004825 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004827 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004828
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004829 ASSERT_TRUE(mDispatcher->waitForIdle());
4830 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004831}
4832
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004833// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4834// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4835TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4836 const MotionEvent event =
4837 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4838 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4839 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4840 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4841 .build();
4842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4843 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4844 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4845
4846 ASSERT_TRUE(mDispatcher->waitForIdle());
4847 mFakePolicy->assertOnPointerDownWasNotCalled();
4848 // Ensure that the unfocused window did not receive any FOCUS events.
4849 mUnfocusedWindow->assertNoEvents();
4850}
4851
chaviwaf87b3e2019-10-01 16:59:28 -07004852// These tests ensures we can send touch events to a single client when there are multiple input
4853// windows that point to the same client token.
4854class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4855 virtual void SetUp() override {
4856 InputDispatcherTest::SetUp();
4857
Chris Yea209fde2020-07-22 13:54:51 -07004858 std::shared_ptr<FakeApplicationHandle> application =
4859 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004860 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4861 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004862 mWindow1->setFrame(Rect(0, 0, 100, 100));
4863
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004864 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4865 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004866 mWindow2->setFrame(Rect(100, 100, 200, 200));
4867
Arthur Hung72d8dc32020-03-28 00:48:39 +00004868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004869 }
4870
4871protected:
4872 sp<FakeWindowHandle> mWindow1;
4873 sp<FakeWindowHandle> mWindow2;
4874
4875 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004876 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004877 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4878 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004879 }
4880
4881 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4882 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004883 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004884 InputEvent* event = window->consume();
4885
4886 ASSERT_NE(nullptr, event) << name.c_str()
4887 << ": consumer should have returned non-NULL event.";
4888
4889 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4890 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4891 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4892
4893 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004894 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08004895 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07004896
4897 for (size_t i = 0; i < points.size(); i++) {
4898 float expectedX = points[i].x;
4899 float expectedY = points[i].y;
4900
4901 EXPECT_EQ(expectedX, motionEvent.getX(i))
4902 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4903 << ", got " << motionEvent.getX(i);
4904 EXPECT_EQ(expectedY, motionEvent.getY(i))
4905 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4906 << ", got " << motionEvent.getY(i);
4907 }
4908 }
chaviw9eaa22c2020-07-01 16:21:27 -07004909
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004910 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004911 std::vector<PointF> expectedPoints) {
4912 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4913 ADISPLAY_ID_DEFAULT, touchedPoints);
4914 mDispatcher->notifyMotion(&motionArgs);
4915
4916 // Always consume from window1 since it's the window that has the InputReceiver
4917 consumeMotionEvent(mWindow1, action, expectedPoints);
4918 }
chaviwaf87b3e2019-10-01 16:59:28 -07004919};
4920
4921TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4922 // Touch Window 1
4923 PointF touchedPoint = {10, 10};
4924 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004925 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004926
4927 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004928 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004929
4930 // Touch Window 2
4931 touchedPoint = {150, 150};
4932 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004933 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004934}
4935
chaviw9eaa22c2020-07-01 16:21:27 -07004936TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4937 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004938 mWindow2->setWindowScale(0.5f, 0.5f);
4939
4940 // Touch Window 1
4941 PointF touchedPoint = {10, 10};
4942 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004943 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004944 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004945 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004946
4947 // Touch Window 2
4948 touchedPoint = {150, 150};
4949 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004950 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4951 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004952
chaviw9eaa22c2020-07-01 16:21:27 -07004953 // Update the transform so rotation is set
4954 mWindow2->setWindowTransform(0, -1, 1, 0);
4955 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4956 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004957}
4958
chaviw9eaa22c2020-07-01 16:21:27 -07004959TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004960 mWindow2->setWindowScale(0.5f, 0.5f);
4961
4962 // Touch Window 1
4963 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4964 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004965 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004966
4967 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004968 touchedPoints.push_back(PointF{150, 150});
4969 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004970 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004971
chaviw9eaa22c2020-07-01 16:21:27 -07004972 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004973 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004974 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004975
chaviw9eaa22c2020-07-01 16:21:27 -07004976 // Update the transform so rotation is set for Window 2
4977 mWindow2->setWindowTransform(0, -1, 1, 0);
4978 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004979 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004980}
4981
chaviw9eaa22c2020-07-01 16:21:27 -07004982TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004983 mWindow2->setWindowScale(0.5f, 0.5f);
4984
4985 // Touch Window 1
4986 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4987 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004988 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004989
4990 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004991 touchedPoints.push_back(PointF{150, 150});
4992 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004993
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004994 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004995
4996 // Move both windows
4997 touchedPoints = {{20, 20}, {175, 175}};
4998 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4999 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5000
chaviw9eaa22c2020-07-01 16:21:27 -07005001 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005002
chaviw9eaa22c2020-07-01 16:21:27 -07005003 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005004 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005005 expectedPoints.pop_back();
5006
5007 // Touch Window 2
5008 mWindow2->setWindowTransform(0, -1, 1, 0);
5009 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005010 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005011
5012 // Move both windows
5013 touchedPoints = {{20, 20}, {175, 175}};
5014 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5015 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5016
5017 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005018}
5019
5020TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
5021 mWindow1->setWindowScale(0.5f, 0.5f);
5022
5023 // Touch Window 1
5024 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5025 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005026 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005027
5028 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005029 touchedPoints.push_back(PointF{150, 150});
5030 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005031
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005032 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005033
5034 // Move both windows
5035 touchedPoints = {{20, 20}, {175, 175}};
5036 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5037 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5038
chaviw9eaa22c2020-07-01 16:21:27 -07005039 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005040}
5041
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005042class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
5043 virtual void SetUp() override {
5044 InputDispatcherTest::SetUp();
5045
Chris Yea209fde2020-07-22 13:54:51 -07005046 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005047 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005048 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
5049 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005050 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005051 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07005052 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005053
5054 // Set focused application.
5055 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
5056
5057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005058 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005059 mWindow->consumeFocusEvent(true);
5060 }
5061
5062 virtual void TearDown() override {
5063 InputDispatcherTest::TearDown();
5064 mWindow.clear();
5065 }
5066
5067protected:
Chris Yea209fde2020-07-22 13:54:51 -07005068 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005069 sp<FakeWindowHandle> mWindow;
5070 static constexpr PointF WINDOW_LOCATION = {20, 20};
5071
5072 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005074 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5075 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005077 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5078 WINDOW_LOCATION));
5079 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005080
5081 sp<FakeWindowHandle> addSpyWindow() {
5082 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005083 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005084 spy->setTrustedOverlay(true);
5085 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005086 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005087 spy->setDispatchingTimeout(30ms);
5088 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
5089 return spy;
5090 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005091};
5092
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005093// Send a tap and respond, which should not cause an ANR.
5094TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
5095 tapOnWindow();
5096 mWindow->consumeMotionDown();
5097 mWindow->consumeMotionUp();
5098 ASSERT_TRUE(mDispatcher->waitForIdle());
5099 mFakePolicy->assertNotifyAnrWasNotCalled();
5100}
5101
5102// Send a regular key and respond, which should not cause an ANR.
5103TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005105 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5106 ASSERT_TRUE(mDispatcher->waitForIdle());
5107 mFakePolicy->assertNotifyAnrWasNotCalled();
5108}
5109
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005110TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
5111 mWindow->setFocusable(false);
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5113 mWindow->consumeFocusEvent(false);
5114
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005115 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005116 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005117 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5118 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005120 // Key will not go to window because we have no focused window.
5121 // The 'no focused window' ANR timer should start instead.
5122
5123 // Now, the focused application goes away.
5124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
5125 // The key should get dropped and there should be no ANR.
5126
5127 ASSERT_TRUE(mDispatcher->waitForIdle());
5128 mFakePolicy->assertNotifyAnrWasNotCalled();
5129}
5130
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005131// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
5133// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005134TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005136 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5137 WINDOW_LOCATION));
5138
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005139 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
5140 ASSERT_TRUE(sequenceNum);
5141 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005142 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005143
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005144 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005145 mWindow->consumeMotionEvent(
5146 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005147 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005148 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005149}
5150
5151// Send a key to the app and have the app not respond right away.
5152TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
5153 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005155 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
5156 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005157 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005158 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005159 ASSERT_TRUE(mDispatcher->waitForIdle());
5160}
5161
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005162// We have a focused application, but no focused window
5163TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005164 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5166 mWindow->consumeFocusEvent(false);
5167
5168 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005169 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005170 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5171 WINDOW_LOCATION));
5172 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
5173 mDispatcher->waitForIdle();
5174 mFakePolicy->assertNotifyAnrWasNotCalled();
5175
5176 // Once a focused event arrives, we get an ANR for this application
5177 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5178 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005179 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005180 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005181 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005182 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005183 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07005184 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005185 ASSERT_TRUE(mDispatcher->waitForIdle());
5186}
5187
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005188/**
5189 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
5190 * there will not be an ANR.
5191 */
5192TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
5193 mWindow->setFocusable(false);
5194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5195 mWindow->consumeFocusEvent(false);
5196
5197 KeyEvent event;
5198 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
5199 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
5200
5201 // Define a valid key down event that is stale (too old).
5202 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
5203 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
5204 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
5205
5206 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
5207
5208 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00005209 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005210 InputEventInjectionSync::WAIT_FOR_RESULT,
5211 INJECT_EVENT_TIMEOUT, policyFlags);
5212 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
5213 << "Injection should fail because the event is stale";
5214
5215 ASSERT_TRUE(mDispatcher->waitForIdle());
5216 mFakePolicy->assertNotifyAnrWasNotCalled();
5217 mWindow->assertNoEvents();
5218}
5219
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005221// Make sure that we don't notify policy twice about the same ANR.
5222TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005223 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5225 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005226
5227 // Once a focused event arrives, we get an ANR for this application
5228 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5229 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005230 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005232 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005233 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005234 const std::chrono::duration appTimeout =
5235 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5236 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237
Vishnu Naire4df8752022-09-08 09:17:55 -07005238 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005239 // ANR should not be raised again. It is up to policy to do that if it desires.
5240 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005242 // If we now get a focused window, the ANR should stop, but the policy handles that via
5243 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244 ASSERT_TRUE(mDispatcher->waitForIdle());
5245}
5246
5247// We have a focused application, but no focused window
5248TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005249 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5251 mWindow->consumeFocusEvent(false);
5252
5253 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005254 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005255 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005256 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5257 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005258
Vishnu Naire4df8752022-09-08 09:17:55 -07005259 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5260 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005261
5262 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005263 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264 ASSERT_TRUE(mDispatcher->waitForIdle());
5265 mWindow->assertNoEvents();
5266}
5267
5268/**
5269 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5270 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5271 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5272 * the ANR mechanism should still work.
5273 *
5274 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5275 * DOWN event, while not responding on the second one.
5276 */
5277TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5278 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5279 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5280 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5281 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5282 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005283 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005284
5285 // Now send ACTION_UP, with identical timestamp
5286 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5287 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5288 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5289 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005290 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005291
5292 // We have now sent down and up. Let's consume first event and then ANR on the second.
5293 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5294 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005295 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005296}
5297
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005298// A spy window can receive an ANR
5299TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5300 sp<FakeWindowHandle> spy = addSpyWindow();
5301
5302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5303 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5304 WINDOW_LOCATION));
5305 mWindow->consumeMotionDown();
5306
5307 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5308 ASSERT_TRUE(sequenceNum);
5309 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005310 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005311
5312 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005313 spy->consumeMotionEvent(
5314 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005315 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005316 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005317}
5318
5319// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005321TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5322 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5325 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005326 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005327 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005328
5329 // Stuck on the ACTION_UP
5330 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005331 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005332
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005333 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005334 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005335 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5336 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337
5338 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5339 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005340 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005342 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005343}
5344
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005345// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005346// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005347TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5348 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005349
5350 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005351 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5352 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005353
5354 mWindow->consumeMotionDown();
5355 // Stuck on the ACTION_UP
5356 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005357 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005359 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005360 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005361 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5362 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005363
5364 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5365 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005366 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005367 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005368 spy->assertNoEvents();
5369}
5370
5371TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5372 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5373
5374 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5375
5376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5377 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5378 WINDOW_LOCATION));
5379
5380 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5381 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5382 ASSERT_TRUE(consumeSeq);
5383
Prabir Pradhanedd96402022-02-15 01:46:16 -08005384 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005385
5386 monitor.finishEvent(*consumeSeq);
5387 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5388
5389 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005390 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005391}
5392
5393// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5394// process events, you don't get an anr. When the window later becomes unresponsive again, you
5395// get an ANR again.
5396// 1. tap -> block on ACTION_UP -> receive ANR
5397// 2. consume all pending events (= queue becomes healthy again)
5398// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5399TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5400 tapOnWindow();
5401
5402 mWindow->consumeMotionDown();
5403 // Block on ACTION_UP
5404 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005405 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005406 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5407 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005408 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005409 mWindow->assertNoEvents();
5410
5411 tapOnWindow();
5412 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005413 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005414 mWindow->consumeMotionUp();
5415
5416 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005417 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005418 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419 mWindow->assertNoEvents();
5420}
5421
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005422// If a connection remains unresponsive for a while, make sure policy is only notified once about
5423// it.
5424TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005426 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5427 WINDOW_LOCATION));
5428
5429 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005430 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005431 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005432 // 'notifyConnectionUnresponsive' should only be called once per connection
5433 mFakePolicy->assertNotifyAnrWasNotCalled();
5434 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005435 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005436 mWindow->consumeMotionEvent(
5437 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005438 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005439 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005440 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005441 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005442}
5443
5444/**
5445 * If a window is processing a motion event, and then a key event comes in, the key event should
5446 * not to to the focused window until the motion is processed.
5447 *
5448 * Warning!!!
5449 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5450 * and the injection timeout that we specify when injecting the key.
5451 * We must have the injection timeout (10ms) be smaller than
5452 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5453 *
5454 * If that value changes, this test should also change.
5455 */
5456TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5457 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5459
5460 tapOnWindow();
5461 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5462 ASSERT_TRUE(downSequenceNum);
5463 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5464 ASSERT_TRUE(upSequenceNum);
5465 // Don't finish the events yet, and send a key
5466 // Injection will "succeed" because we will eventually give up and send the key to the focused
5467 // window even if motions are still being processed. But because the injection timeout is short,
5468 // we will receive INJECTION_TIMED_OUT as the result.
5469
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005470 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005471 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005472 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5473 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005474 // Key will not be sent to the window, yet, because the window is still processing events
5475 // and the key remains pending, waiting for the touch events to be processed
5476 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5477 ASSERT_FALSE(keySequenceNum);
5478
5479 std::this_thread::sleep_for(500ms);
5480 // if we wait long enough though, dispatcher will give up, and still send the key
5481 // to the focused window, even though we have not yet finished the motion event
5482 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5483 mWindow->finishEvent(*downSequenceNum);
5484 mWindow->finishEvent(*upSequenceNum);
5485}
5486
5487/**
5488 * If a window is processing a motion event, and then a key event comes in, the key event should
5489 * not go to the focused window until the motion is processed.
5490 * If then a new motion comes in, then the pending key event should be going to the currently
5491 * focused window right away.
5492 */
5493TEST_F(InputDispatcherSingleWindowAnr,
5494 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5495 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5497
5498 tapOnWindow();
5499 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5500 ASSERT_TRUE(downSequenceNum);
5501 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5502 ASSERT_TRUE(upSequenceNum);
5503 // Don't finish the events yet, and send a key
5504 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005506 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005507 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005508 // At this point, key is still pending, and should not be sent to the application yet.
5509 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5510 ASSERT_FALSE(keySequenceNum);
5511
5512 // Now tap down again. It should cause the pending key to go to the focused window right away.
5513 tapOnWindow();
5514 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5515 // the other events yet. We can finish events in any order.
5516 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5517 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5518 mWindow->consumeMotionDown();
5519 mWindow->consumeMotionUp();
5520 mWindow->assertNoEvents();
5521}
5522
5523class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5524 virtual void SetUp() override {
5525 InputDispatcherTest::SetUp();
5526
Chris Yea209fde2020-07-22 13:54:51 -07005527 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005529 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5530 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005531 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005533 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005534
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005535 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5536 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005537 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005538 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005539
5540 // Set focused application.
5541 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005542 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005543
5544 // Expect one focus window exist in display.
5545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005546 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 mFocusedWindow->consumeFocusEvent(true);
5548 }
5549
5550 virtual void TearDown() override {
5551 InputDispatcherTest::TearDown();
5552
5553 mUnfocusedWindow.clear();
5554 mFocusedWindow.clear();
5555 }
5556
5557protected:
Chris Yea209fde2020-07-22 13:54:51 -07005558 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005559 sp<FakeWindowHandle> mUnfocusedWindow;
5560 sp<FakeWindowHandle> mFocusedWindow;
5561 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5562 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5563 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5564
5565 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5566
5567 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5568
5569private:
5570 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5573 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005575 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5576 location));
5577 }
5578};
5579
5580// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5581// should be ANR'd first.
5582TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5585 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005587 mFocusedWindow->consumeMotionDown();
5588 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5589 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5590 // We consumed all events, so no ANR
5591 ASSERT_TRUE(mDispatcher->waitForIdle());
5592 mFakePolicy->assertNotifyAnrWasNotCalled();
5593
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5596 FOCUSED_WINDOW_LOCATION));
5597 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5598 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005599
5600 const std::chrono::duration timeout =
5601 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005602 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005603 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5604 // sequence to make it consistent
5605 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005606 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005607 mFocusedWindow->consumeMotionDown();
5608 // This cancel is generated because the connection was unresponsive
5609 mFocusedWindow->consumeMotionCancel();
5610 mFocusedWindow->assertNoEvents();
5611 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005612 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005613 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5614 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005615 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005616}
5617
5618// If we have 2 windows with identical timeouts that are both unresponsive,
5619// it doesn't matter which order they should have ANR.
5620// But we should receive ANR for both.
5621TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5622 // Set the timeout for unfocused window to match the focused window
5623 mUnfocusedWindow->setDispatchingTimeout(10ms);
5624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5625
5626 tapOnFocusedWindow();
5627 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005628 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5629 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5630 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005631
5632 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005633 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5634 mFocusedWindow->getToken() == anrConnectionToken2);
5635 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5636 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005637
5638 ASSERT_TRUE(mDispatcher->waitForIdle());
5639 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005640
5641 mFocusedWindow->consumeMotionDown();
5642 mFocusedWindow->consumeMotionUp();
5643 mUnfocusedWindow->consumeMotionOutside();
5644
Prabir Pradhanedd96402022-02-15 01:46:16 -08005645 sp<IBinder> responsiveToken1, responsiveToken2;
5646 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5647 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005648
5649 // Both applications should be marked as responsive, in any order
5650 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5651 mFocusedWindow->getToken() == responsiveToken2);
5652 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5653 mUnfocusedWindow->getToken() == responsiveToken2);
5654 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005655}
5656
5657// If a window is already not responding, the second tap on the same window should be ignored.
5658// We should also log an error to account for the dropped event (not tested here).
5659// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5660TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5661 tapOnFocusedWindow();
5662 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5663 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5664 // Receive the events, but don't respond
5665 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5666 ASSERT_TRUE(downEventSequenceNum);
5667 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5668 ASSERT_TRUE(upEventSequenceNum);
5669 const std::chrono::duration timeout =
5670 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005671 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672
5673 // Tap once again
5674 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005675 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005676 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5677 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005678 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005679 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5680 FOCUSED_WINDOW_LOCATION));
5681 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5682 // valid touch target
5683 mUnfocusedWindow->assertNoEvents();
5684
5685 // Consume the first tap
5686 mFocusedWindow->finishEvent(*downEventSequenceNum);
5687 mFocusedWindow->finishEvent(*upEventSequenceNum);
5688 ASSERT_TRUE(mDispatcher->waitForIdle());
5689 // The second tap did not go to the focused window
5690 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005691 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005692 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5693 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005694 mFakePolicy->assertNotifyAnrWasNotCalled();
5695}
5696
5697// If you tap outside of all windows, there will not be ANR
5698TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005699 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5701 LOCATION_OUTSIDE_ALL_WINDOWS));
5702 ASSERT_TRUE(mDispatcher->waitForIdle());
5703 mFakePolicy->assertNotifyAnrWasNotCalled();
5704}
5705
5706// Since the focused window is paused, tapping on it should not produce any events
5707TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5708 mFocusedWindow->setPaused(true);
5709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005711 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5713 FOCUSED_WINDOW_LOCATION));
5714
5715 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5716 ASSERT_TRUE(mDispatcher->waitForIdle());
5717 // Should not ANR because the window is paused, and touches shouldn't go to it
5718 mFakePolicy->assertNotifyAnrWasNotCalled();
5719
5720 mFocusedWindow->assertNoEvents();
5721 mUnfocusedWindow->assertNoEvents();
5722}
5723
5724/**
5725 * If a window is processing a motion event, and then a key event comes in, the key event should
5726 * not to to the focused window until the motion is processed.
5727 * If a different window becomes focused at this time, the key should go to that window instead.
5728 *
5729 * Warning!!!
5730 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5731 * and the injection timeout that we specify when injecting the key.
5732 * We must have the injection timeout (10ms) be smaller than
5733 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5734 *
5735 * If that value changes, this test should also change.
5736 */
5737TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5738 // Set a long ANR timeout to prevent it from triggering
5739 mFocusedWindow->setDispatchingTimeout(2s);
5740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5741
5742 tapOnUnfocusedWindow();
5743 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5744 ASSERT_TRUE(downSequenceNum);
5745 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5746 ASSERT_TRUE(upSequenceNum);
5747 // Don't finish the events yet, and send a key
5748 // Injection will succeed because we will eventually give up and send the key to the focused
5749 // window even if motions are still being processed.
5750
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005751 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005752 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005753 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755 // Key will not be sent to the window, yet, because the window is still processing events
5756 // and the key remains pending, waiting for the touch events to be processed
5757 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5758 ASSERT_FALSE(keySequenceNum);
5759
5760 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005761 mFocusedWindow->setFocusable(false);
5762 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005764 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005765
5766 // Focus events should precede the key events
5767 mUnfocusedWindow->consumeFocusEvent(true);
5768 mFocusedWindow->consumeFocusEvent(false);
5769
5770 // Finish the tap events, which should unblock dispatcher
5771 mUnfocusedWindow->finishEvent(*downSequenceNum);
5772 mUnfocusedWindow->finishEvent(*upSequenceNum);
5773
5774 // Now that all queues are cleared and no backlog in the connections, the key event
5775 // can finally go to the newly focused "mUnfocusedWindow".
5776 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5777 mFocusedWindow->assertNoEvents();
5778 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005779 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005780}
5781
5782// When the touch stream is split across 2 windows, and one of them does not respond,
5783// then ANR should be raised and the touch should be canceled for the unresponsive window.
5784// The other window should not be affected by that.
5785TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5786 // Touch Window 1
5787 NotifyMotionArgs motionArgs =
5788 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5789 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5790 mDispatcher->notifyMotion(&motionArgs);
5791 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5792 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5793
5794 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005795 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5796 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005797 mDispatcher->notifyMotion(&motionArgs);
5798
5799 const std::chrono::duration timeout =
5800 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005801 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005802
5803 mUnfocusedWindow->consumeMotionDown();
5804 mFocusedWindow->consumeMotionDown();
5805 // Focused window may or may not receive ACTION_MOVE
5806 // But it should definitely receive ACTION_CANCEL due to the ANR
5807 InputEvent* event;
5808 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5809 ASSERT_TRUE(moveOrCancelSequenceNum);
5810 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5811 ASSERT_NE(nullptr, event);
5812 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5813 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5814 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5815 mFocusedWindow->consumeMotionCancel();
5816 } else {
5817 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5818 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005819 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005820 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5821 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005822
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005823 mUnfocusedWindow->assertNoEvents();
5824 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005825 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005826}
5827
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005828/**
5829 * If we have no focused window, and a key comes in, we start the ANR timer.
5830 * The focused application should add a focused window before the timer runs out to prevent ANR.
5831 *
5832 * If the user touches another application during this time, the key should be dropped.
5833 * Next, if a new focused window comes in, without toggling the focused application,
5834 * then no ANR should occur.
5835 *
5836 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5837 * but in some cases the policy may not update the focused application.
5838 */
5839TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5840 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5841 std::make_shared<FakeApplicationHandle>();
5842 focusedApplication->setDispatchingTimeout(60ms);
5843 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5844 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5845 mFocusedWindow->setFocusable(false);
5846
5847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5848 mFocusedWindow->consumeFocusEvent(false);
5849
5850 // Send a key. The ANR timer should start because there is no focused window.
5851 // 'focusedApplication' will get blamed if this timer completes.
5852 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005853 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005854 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005855 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5856 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005858
5859 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5860 // then the injected touches won't cause the focused event to get dropped.
5861 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5862 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5863 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5864 // For this test, it means that the key would get delivered to the window once it becomes
5865 // focused.
5866 std::this_thread::sleep_for(10ms);
5867
5868 // Touch unfocused window. This should force the pending key to get dropped.
5869 NotifyMotionArgs motionArgs =
5870 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5871 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5872 mDispatcher->notifyMotion(&motionArgs);
5873
5874 // We do not consume the motion right away, because that would require dispatcher to first
5875 // process (== drop) the key event, and by that time, ANR will be raised.
5876 // Set the focused window first.
5877 mFocusedWindow->setFocusable(true);
5878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5879 setFocusedWindow(mFocusedWindow);
5880 mFocusedWindow->consumeFocusEvent(true);
5881 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5882 // to another application. This could be a bug / behaviour in the policy.
5883
5884 mUnfocusedWindow->consumeMotionDown();
5885
5886 ASSERT_TRUE(mDispatcher->waitForIdle());
5887 // Should not ANR because we actually have a focused window. It was just added too slowly.
5888 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5889}
5890
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005891// These tests ensure we cannot send touch events to a window that's positioned behind a window
5892// that has feature NO_INPUT_CHANNEL.
5893// Layout:
5894// Top (closest to user)
5895// mNoInputWindow (above all windows)
5896// mBottomWindow
5897// Bottom (furthest from user)
5898class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5899 virtual void SetUp() override {
5900 InputDispatcherTest::SetUp();
5901
5902 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005903 mNoInputWindow =
5904 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5905 "Window without input channel", ADISPLAY_ID_DEFAULT,
5906 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005907 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005908 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5909 // It's perfectly valid for this window to not have an associated input channel
5910
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005911 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5912 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005913 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5914
5915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5916 }
5917
5918protected:
5919 std::shared_ptr<FakeApplicationHandle> mApplication;
5920 sp<FakeWindowHandle> mNoInputWindow;
5921 sp<FakeWindowHandle> mBottomWindow;
5922};
5923
5924TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5925 PointF touchedPoint = {10, 10};
5926
5927 NotifyMotionArgs motionArgs =
5928 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5929 ADISPLAY_ID_DEFAULT, {touchedPoint});
5930 mDispatcher->notifyMotion(&motionArgs);
5931
5932 mNoInputWindow->assertNoEvents();
5933 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5934 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5935 // and therefore should prevent mBottomWindow from receiving touches
5936 mBottomWindow->assertNoEvents();
5937}
5938
5939/**
5940 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5941 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5942 */
5943TEST_F(InputDispatcherMultiWindowOcclusionTests,
5944 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005945 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5946 "Window with input channel and NO_INPUT_CHANNEL",
5947 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005948
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005949 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005950 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5952
5953 PointF touchedPoint = {10, 10};
5954
5955 NotifyMotionArgs motionArgs =
5956 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5957 ADISPLAY_ID_DEFAULT, {touchedPoint});
5958 mDispatcher->notifyMotion(&motionArgs);
5959
5960 mNoInputWindow->assertNoEvents();
5961 mBottomWindow->assertNoEvents();
5962}
5963
Vishnu Nair958da932020-08-21 17:12:37 -07005964class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5965protected:
5966 std::shared_ptr<FakeApplicationHandle> mApp;
5967 sp<FakeWindowHandle> mWindow;
5968 sp<FakeWindowHandle> mMirror;
5969
5970 virtual void SetUp() override {
5971 InputDispatcherTest::SetUp();
5972 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005973 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5974 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5975 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005976 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5977 mWindow->setFocusable(true);
5978 mMirror->setFocusable(true);
5979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5980 }
5981};
5982
5983TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5984 // Request focus on a mirrored window
5985 setFocusedWindow(mMirror);
5986
5987 // window gets focused
5988 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5990 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005991 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5992}
5993
5994// A focused & mirrored window remains focused only if the window and its mirror are both
5995// focusable.
5996TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5997 setFocusedWindow(mMirror);
5998
5999 // window gets focused
6000 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6002 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006003 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6005 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006006 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6007
6008 mMirror->setFocusable(false);
6009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6010
6011 // window loses focus since one of the windows associated with the token in not focusable
6012 mWindow->consumeFocusEvent(false);
6013
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006014 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6015 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006016 mWindow->assertNoEvents();
6017}
6018
6019// A focused & mirrored window remains focused until the window and its mirror both become
6020// invisible.
6021TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
6022 setFocusedWindow(mMirror);
6023
6024 // window gets focused
6025 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6027 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006028 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6030 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006031 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6032
6033 mMirror->setVisible(false);
6034 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6035
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6037 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006038 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6040 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006041 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6042
6043 mWindow->setVisible(false);
6044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6045
6046 // window loses focus only after all windows associated with the token become invisible.
6047 mWindow->consumeFocusEvent(false);
6048
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006049 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6050 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006051 mWindow->assertNoEvents();
6052}
6053
6054// A focused & mirrored window remains focused until both windows are removed.
6055TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
6056 setFocusedWindow(mMirror);
6057
6058 // window gets focused
6059 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6061 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006062 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6064 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006065 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6066
6067 // single window is removed but the window token remains focused
6068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
6069
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6071 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006072 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6074 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006075 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6076
6077 // Both windows are removed
6078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
6079 mWindow->consumeFocusEvent(false);
6080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006081 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6082 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006083 mWindow->assertNoEvents();
6084}
6085
6086// Focus request can be pending until one window becomes visible.
6087TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
6088 // Request focus on an invisible mirror.
6089 mWindow->setVisible(false);
6090 mMirror->setVisible(false);
6091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6092 setFocusedWindow(mMirror);
6093
6094 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07006096 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006097 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07006098
6099 mMirror->setVisible(true);
6100 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6101
6102 // window gets focused
6103 mWindow->consumeFocusEvent(true);
6104 // window gets the pending key event
6105 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6106}
Prabir Pradhan99987712020-11-10 18:43:05 -08006107
6108class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
6109protected:
6110 std::shared_ptr<FakeApplicationHandle> mApp;
6111 sp<FakeWindowHandle> mWindow;
6112 sp<FakeWindowHandle> mSecondWindow;
6113
6114 void SetUp() override {
6115 InputDispatcherTest::SetUp();
6116 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006117 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006118 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006119 mSecondWindow =
6120 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006121 mSecondWindow->setFocusable(true);
6122
6123 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6125
6126 setFocusedWindow(mWindow);
6127 mWindow->consumeFocusEvent(true);
6128 }
6129
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006130 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
6131 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006132 mDispatcher->notifyPointerCaptureChanged(&args);
6133 }
6134
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006135 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
6136 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006137 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006138 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
6139 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006140 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006141 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08006142 }
6143};
6144
6145TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
6146 // Ensure that capture cannot be obtained for unfocused windows.
6147 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
6148 mFakePolicy->assertSetPointerCaptureNotCalled();
6149 mSecondWindow->assertNoEvents();
6150
6151 // Ensure that capture can be enabled from the focus window.
6152 requestAndVerifyPointerCapture(mWindow, true);
6153
6154 // Ensure that capture cannot be disabled from a window that does not have capture.
6155 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
6156 mFakePolicy->assertSetPointerCaptureNotCalled();
6157
6158 // Ensure that capture can be disabled from the window with capture.
6159 requestAndVerifyPointerCapture(mWindow, false);
6160}
6161
6162TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006163 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006164
6165 setFocusedWindow(mSecondWindow);
6166
6167 // Ensure that the capture disabled event was sent first.
6168 mWindow->consumeCaptureEvent(false);
6169 mWindow->consumeFocusEvent(false);
6170 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006171 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006172
6173 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006174 notifyPointerCaptureChanged({});
6175 notifyPointerCaptureChanged(request);
6176 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08006177 mWindow->assertNoEvents();
6178 mSecondWindow->assertNoEvents();
6179 mFakePolicy->assertSetPointerCaptureNotCalled();
6180}
6181
6182TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006183 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006184
6185 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006186 notifyPointerCaptureChanged({});
6187 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006188
6189 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006190 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006191 mWindow->consumeCaptureEvent(false);
6192 mWindow->assertNoEvents();
6193}
6194
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006195TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
6196 requestAndVerifyPointerCapture(mWindow, true);
6197
6198 // The first window loses focus.
6199 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006200 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006201 mWindow->consumeCaptureEvent(false);
6202
6203 // Request Pointer Capture from the second window before the notification from InputReader
6204 // arrives.
6205 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006206 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006207
6208 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006209 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006210
6211 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006212 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006213
6214 mSecondWindow->consumeFocusEvent(true);
6215 mSecondWindow->consumeCaptureEvent(true);
6216}
6217
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006218TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
6219 // App repeatedly enables and disables capture.
6220 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6221 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6222 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6223 mFakePolicy->assertSetPointerCaptureCalled(false);
6224 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6225 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6226
6227 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6228 // first request is now stale, this should do nothing.
6229 notifyPointerCaptureChanged(firstRequest);
6230 mWindow->assertNoEvents();
6231
6232 // InputReader notifies that the second request was enabled.
6233 notifyPointerCaptureChanged(secondRequest);
6234 mWindow->consumeCaptureEvent(true);
6235}
6236
Prabir Pradhan7092e262022-05-03 16:51:09 +00006237TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6238 requestAndVerifyPointerCapture(mWindow, true);
6239
6240 // App toggles pointer capture off and on.
6241 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6242 mFakePolicy->assertSetPointerCaptureCalled(false);
6243
6244 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6245 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6246
6247 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6248 // preceding "disable" request.
6249 notifyPointerCaptureChanged(enableRequest);
6250
6251 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6252 // any notifications.
6253 mWindow->assertNoEvents();
6254}
6255
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006256class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6257protected:
6258 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006259
6260 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6261 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6262
6263 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6264 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6265
6266 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6267 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6268 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6269 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6270 MAXIMUM_OBSCURING_OPACITY);
6271
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006272 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006273 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006274 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006275
6276 sp<FakeWindowHandle> mTouchWindow;
6277
6278 virtual void SetUp() override {
6279 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006280 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006281 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6282 }
6283
6284 virtual void TearDown() override {
6285 InputDispatcherTest::TearDown();
6286 mTouchWindow.clear();
6287 }
6288
chaviw3277faf2021-05-19 16:45:23 -05006289 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6290 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006291 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006292 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006293 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006294 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006295 return window;
6296 }
6297
6298 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6299 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6300 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006301 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006302 // Generate an arbitrary PID based on the UID
6303 window->setOwnerInfo(1777 + (uid % 10000), uid);
6304 return window;
6305 }
6306
6307 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6308 NotifyMotionArgs args =
6309 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6310 ADISPLAY_ID_DEFAULT, points);
6311 mDispatcher->notifyMotion(&args);
6312 }
6313};
6314
6315TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006316 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006317 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006319
6320 touch();
6321
6322 mTouchWindow->assertNoEvents();
6323}
6324
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006325TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006326 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6327 const sp<FakeWindowHandle>& w =
6328 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6330
6331 touch();
6332
6333 mTouchWindow->assertNoEvents();
6334}
6335
6336TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006337 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6338 const sp<FakeWindowHandle>& w =
6339 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6341
6342 touch();
6343
6344 w->assertNoEvents();
6345}
6346
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006347TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006348 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006350
6351 touch();
6352
6353 mTouchWindow->consumeAnyMotionDown();
6354}
6355
6356TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006357 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006358 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006359 w->setFrame(Rect(0, 0, 50, 50));
6360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006361
6362 touch({PointF{100, 100}});
6363
6364 mTouchWindow->consumeAnyMotionDown();
6365}
6366
6367TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006368 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006369 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6371
6372 touch();
6373
6374 mTouchWindow->consumeAnyMotionDown();
6375}
6376
6377TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6378 const sp<FakeWindowHandle>& w =
6379 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006381
6382 touch();
6383
6384 mTouchWindow->consumeAnyMotionDown();
6385}
6386
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006387TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6388 const sp<FakeWindowHandle>& w =
6389 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6391
6392 touch();
6393
6394 w->assertNoEvents();
6395}
6396
6397/**
6398 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6399 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6400 * window, the occluding window will still receive ACTION_OUTSIDE event.
6401 */
6402TEST_F(InputDispatcherUntrustedTouchesTest,
6403 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6404 const sp<FakeWindowHandle>& w =
6405 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006406 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6408
6409 touch();
6410
6411 w->consumeMotionOutside();
6412}
6413
6414TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6415 const sp<FakeWindowHandle>& w =
6416 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006417 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6419
6420 touch();
6421
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006422 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006423}
6424
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006425TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006426 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006427 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6428 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6430
6431 touch();
6432
6433 mTouchWindow->consumeAnyMotionDown();
6434}
6435
6436TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6437 const sp<FakeWindowHandle>& w =
6438 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6439 MAXIMUM_OBSCURING_OPACITY);
6440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006441
6442 touch();
6443
6444 mTouchWindow->consumeAnyMotionDown();
6445}
6446
6447TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006448 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006449 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6450 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6452
6453 touch();
6454
6455 mTouchWindow->assertNoEvents();
6456}
6457
6458TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6459 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6460 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006461 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6462 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006463 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006464 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6465 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6467
6468 touch();
6469
6470 mTouchWindow->assertNoEvents();
6471}
6472
6473TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6474 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6475 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006476 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6477 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006478 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006479 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6480 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6482
6483 touch();
6484
6485 mTouchWindow->consumeAnyMotionDown();
6486}
6487
6488TEST_F(InputDispatcherUntrustedTouchesTest,
6489 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6490 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006491 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6492 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006493 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006494 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6495 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6497
6498 touch();
6499
6500 mTouchWindow->consumeAnyMotionDown();
6501}
6502
6503TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6504 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 Rufino1d0d1f22021-02-12 15:08:43 +00006507 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006508 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6509 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006511
6512 touch();
6513
6514 mTouchWindow->assertNoEvents();
6515}
6516
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006517TEST_F(InputDispatcherUntrustedTouchesTest,
6518 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6519 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006520 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6521 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006522 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6524 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6526
6527 touch();
6528
6529 mTouchWindow->assertNoEvents();
6530}
6531
6532TEST_F(InputDispatcherUntrustedTouchesTest,
6533 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6534 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006535 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6536 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006537 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006538 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6539 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6541
6542 touch();
6543
6544 mTouchWindow->consumeAnyMotionDown();
6545}
6546
6547TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6548 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006549 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6550 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6552
6553 touch();
6554
6555 mTouchWindow->consumeAnyMotionDown();
6556}
6557
6558TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6559 const sp<FakeWindowHandle>& w =
6560 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6562
6563 touch();
6564
6565 mTouchWindow->consumeAnyMotionDown();
6566}
6567
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006568TEST_F(InputDispatcherUntrustedTouchesTest,
6569 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6570 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6571 const sp<FakeWindowHandle>& w =
6572 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6574
6575 touch();
6576
6577 mTouchWindow->assertNoEvents();
6578}
6579
6580TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6581 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6582 const sp<FakeWindowHandle>& w =
6583 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6585
6586 touch();
6587
6588 mTouchWindow->consumeAnyMotionDown();
6589}
6590
6591TEST_F(InputDispatcherUntrustedTouchesTest,
6592 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6593 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6594 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006595 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6596 OPACITY_ABOVE_THRESHOLD);
6597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6598
6599 touch();
6600
6601 mTouchWindow->consumeAnyMotionDown();
6602}
6603
6604TEST_F(InputDispatcherUntrustedTouchesTest,
6605 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6606 const sp<FakeWindowHandle>& w1 =
6607 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6608 OPACITY_BELOW_THRESHOLD);
6609 const sp<FakeWindowHandle>& w2 =
6610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6611 OPACITY_BELOW_THRESHOLD);
6612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6613
6614 touch();
6615
6616 mTouchWindow->assertNoEvents();
6617}
6618
6619/**
6620 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6621 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6622 * (which alone would result in allowing touches) does not affect the blocking behavior.
6623 */
6624TEST_F(InputDispatcherUntrustedTouchesTest,
6625 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6626 const sp<FakeWindowHandle>& wB =
6627 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6628 OPACITY_BELOW_THRESHOLD);
6629 const sp<FakeWindowHandle>& wC =
6630 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6631 OPACITY_BELOW_THRESHOLD);
6632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6633
6634 touch();
6635
6636 mTouchWindow->assertNoEvents();
6637}
6638
6639/**
6640 * This test is testing that a window from a different UID but with same application token doesn't
6641 * block the touch. Apps can share the application token for close UI collaboration for example.
6642 */
6643TEST_F(InputDispatcherUntrustedTouchesTest,
6644 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6645 const sp<FakeWindowHandle>& w =
6646 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6647 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6649
6650 touch();
6651
6652 mTouchWindow->consumeAnyMotionDown();
6653}
6654
arthurhungb89ccb02020-12-30 16:19:01 +08006655class InputDispatcherDragTests : public InputDispatcherTest {
6656protected:
6657 std::shared_ptr<FakeApplicationHandle> mApp;
6658 sp<FakeWindowHandle> mWindow;
6659 sp<FakeWindowHandle> mSecondWindow;
6660 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006661 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006662 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6663 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006664
6665 void SetUp() override {
6666 InputDispatcherTest::SetUp();
6667 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006668 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006669 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006670
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006671 mSecondWindow =
6672 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006673 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006674
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006675 mSpyWindow =
6676 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006677 mSpyWindow->setSpy(true);
6678 mSpyWindow->setTrustedOverlay(true);
6679 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6680
arthurhungb89ccb02020-12-30 16:19:01 +08006681 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006683 }
6684
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006685 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6686 switch (fromSource) {
6687 case AINPUT_SOURCE_TOUCHSCREEN:
6688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6689 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6690 ADISPLAY_ID_DEFAULT, {50, 50}))
6691 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6692 break;
6693 case AINPUT_SOURCE_STYLUS:
6694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6695 injectMotionEvent(
6696 mDispatcher,
6697 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6698 AINPUT_SOURCE_STYLUS)
6699 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6700 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6701 .x(50)
6702 .y(50))
6703 .build()));
6704 break;
6705 case AINPUT_SOURCE_MOUSE:
6706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6707 injectMotionEvent(
6708 mDispatcher,
6709 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6710 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6711 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6712 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6713 .x(50)
6714 .y(50))
6715 .build()));
6716 break;
6717 default:
6718 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6719 }
arthurhungb89ccb02020-12-30 16:19:01 +08006720
6721 // Window should receive motion event.
6722 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006723 // Spy window should also receive motion event
6724 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006725 }
6726
6727 // Start performing drag, we will create a drag window and transfer touch to it.
6728 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6729 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006730 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006731 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006732 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006733 }
arthurhungb89ccb02020-12-30 16:19:01 +08006734
6735 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006736 mDragWindow =
6737 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006738 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006739 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006740 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006741
6742 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006743 bool transferred =
6744 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6745 true /* isDragDrop */);
6746 if (transferred) {
6747 mWindow->consumeMotionCancel();
6748 mDragWindow->consumeMotionDown();
6749 }
6750 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006751 }
6752};
6753
6754TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006755 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006756
6757 // Move on window.
6758 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6759 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6760 ADISPLAY_ID_DEFAULT, {50, 50}))
6761 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6762 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6763 mWindow->consumeDragEvent(false, 50, 50);
6764 mSecondWindow->assertNoEvents();
6765
6766 // Move to another window.
6767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6768 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6769 ADISPLAY_ID_DEFAULT, {150, 50}))
6770 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6771 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6772 mWindow->consumeDragEvent(true, 150, 50);
6773 mSecondWindow->consumeDragEvent(false, 50, 50);
6774
6775 // Move back to original window.
6776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6777 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6778 ADISPLAY_ID_DEFAULT, {50, 50}))
6779 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6780 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6781 mWindow->consumeDragEvent(false, 50, 50);
6782 mSecondWindow->consumeDragEvent(true, -50, 50);
6783
6784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6785 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6786 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6787 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6788 mWindow->assertNoEvents();
6789 mSecondWindow->assertNoEvents();
6790}
6791
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006792TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006793 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006794
6795 // No cancel event after drag start
6796 mSpyWindow->assertNoEvents();
6797
6798 const MotionEvent secondFingerDownEvent =
6799 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6800 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6801 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6802 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6803 .build();
6804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6805 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6806 InputEventInjectionSync::WAIT_FOR_RESULT))
6807 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6808
6809 // Receives cancel for first pointer after next pointer down
6810 mSpyWindow->consumeMotionCancel();
6811 mSpyWindow->consumeMotionDown();
6812
6813 mSpyWindow->assertNoEvents();
6814}
6815
arthurhungf452d0b2021-01-06 00:19:52 +08006816TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006817 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006818
6819 // Move on window.
6820 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6821 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6822 ADISPLAY_ID_DEFAULT, {50, 50}))
6823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6824 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6825 mWindow->consumeDragEvent(false, 50, 50);
6826 mSecondWindow->assertNoEvents();
6827
6828 // Move to another window.
6829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6830 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6831 ADISPLAY_ID_DEFAULT, {150, 50}))
6832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6833 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6834 mWindow->consumeDragEvent(true, 150, 50);
6835 mSecondWindow->consumeDragEvent(false, 50, 50);
6836
6837 // drop to another window.
6838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6839 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6840 {150, 50}))
6841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6842 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6843 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6844 mWindow->assertNoEvents();
6845 mSecondWindow->assertNoEvents();
6846}
6847
arthurhung6d4bed92021-03-17 11:59:33 +08006848TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006849 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006850
6851 // Move on window and keep button pressed.
6852 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6853 injectMotionEvent(mDispatcher,
6854 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6855 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6856 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6857 .x(50)
6858 .y(50))
6859 .build()))
6860 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6861 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6862 mWindow->consumeDragEvent(false, 50, 50);
6863 mSecondWindow->assertNoEvents();
6864
6865 // Move to another window and release button, expect to drop item.
6866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6867 injectMotionEvent(mDispatcher,
6868 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6869 .buttonState(0)
6870 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6871 .x(150)
6872 .y(50))
6873 .build()))
6874 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6875 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6876 mWindow->assertNoEvents();
6877 mSecondWindow->assertNoEvents();
6878 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6879
6880 // nothing to the window.
6881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6882 injectMotionEvent(mDispatcher,
6883 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6884 .buttonState(0)
6885 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6886 .x(150)
6887 .y(50))
6888 .build()))
6889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6890 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6891 mWindow->assertNoEvents();
6892 mSecondWindow->assertNoEvents();
6893}
6894
Arthur Hung54745652022-04-20 07:17:41 +00006895TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006896 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006897
6898 // Set second window invisible.
6899 mSecondWindow->setVisible(false);
6900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6901
6902 // Move on window.
6903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6904 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6905 ADISPLAY_ID_DEFAULT, {50, 50}))
6906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6907 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6908 mWindow->consumeDragEvent(false, 50, 50);
6909 mSecondWindow->assertNoEvents();
6910
6911 // Move to another window.
6912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6913 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6914 ADISPLAY_ID_DEFAULT, {150, 50}))
6915 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6916 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6917 mWindow->consumeDragEvent(true, 150, 50);
6918 mSecondWindow->assertNoEvents();
6919
6920 // drop to another window.
6921 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6922 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6923 {150, 50}))
6924 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6925 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6926 mFakePolicy->assertDropTargetEquals(nullptr);
6927 mWindow->assertNoEvents();
6928 mSecondWindow->assertNoEvents();
6929}
6930
Arthur Hung54745652022-04-20 07:17:41 +00006931TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006932 // Ensure window could track pointerIds if it didn't support split touch.
6933 mWindow->setPreventSplitting(true);
6934
Arthur Hung54745652022-04-20 07:17:41 +00006935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6937 {50, 50}))
6938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6939 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6940
6941 const MotionEvent secondFingerDownEvent =
6942 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6943 .displayId(ADISPLAY_ID_DEFAULT)
6944 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6945 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6946 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6947 .build();
6948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6949 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6950 InputEventInjectionSync::WAIT_FOR_RESULT))
6951 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6952 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6953
6954 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006955 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006956}
6957
6958TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6959 // First down on second window.
6960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6961 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6962 {150, 50}))
6963 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6964
6965 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6966
6967 // Second down on first window.
6968 const MotionEvent secondFingerDownEvent =
6969 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6970 .displayId(ADISPLAY_ID_DEFAULT)
6971 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6972 .pointer(
6973 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6974 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6975 .build();
6976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6977 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6978 InputEventInjectionSync::WAIT_FOR_RESULT))
6979 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6980 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6981
6982 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006983 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006984
6985 // Move on window.
6986 const MotionEvent secondFingerMoveEvent =
6987 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6988 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6989 .pointer(
6990 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6991 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6992 .build();
6993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6994 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6995 InputEventInjectionSync::WAIT_FOR_RESULT));
6996 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6997 mWindow->consumeDragEvent(false, 50, 50);
6998 mSecondWindow->consumeMotionMove();
6999
7000 // Release the drag pointer should perform drop.
7001 const MotionEvent secondFingerUpEvent =
7002 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
7003 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7004 .pointer(
7005 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7006 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7007 .build();
7008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7009 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
7010 InputEventInjectionSync::WAIT_FOR_RESULT));
7011 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7012 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
7013 mWindow->assertNoEvents();
7014 mSecondWindow->consumeMotionMove();
7015}
7016
Arthur Hung3915c1f2022-05-31 07:17:17 +00007017TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007018 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00007019
7020 // Update window of second display.
7021 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007022 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00007023 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7024
7025 // Let second display has a touch state.
7026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7027 injectMotionEvent(mDispatcher,
7028 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7029 AINPUT_SOURCE_TOUCHSCREEN)
7030 .displayId(SECOND_DISPLAY_ID)
7031 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7032 .x(100)
7033 .y(100))
7034 .build()));
7035 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
7036 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
7037 // Update window again.
7038 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7039
7040 // Move on window.
7041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7042 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7043 ADISPLAY_ID_DEFAULT, {50, 50}))
7044 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7045 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7046 mWindow->consumeDragEvent(false, 50, 50);
7047 mSecondWindow->assertNoEvents();
7048
7049 // Move to another window.
7050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7051 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7052 ADISPLAY_ID_DEFAULT, {150, 50}))
7053 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7054 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7055 mWindow->consumeDragEvent(true, 150, 50);
7056 mSecondWindow->consumeDragEvent(false, 50, 50);
7057
7058 // drop to another window.
7059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7060 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7061 {150, 50}))
7062 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7063 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7064 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7065 mWindow->assertNoEvents();
7066 mSecondWindow->assertNoEvents();
7067}
7068
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007069TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
7070 startDrag(true, AINPUT_SOURCE_MOUSE);
7071 // Move on window.
7072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7073 injectMotionEvent(mDispatcher,
7074 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7075 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7076 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7077 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7078 .x(50)
7079 .y(50))
7080 .build()))
7081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7082 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7083 mWindow->consumeDragEvent(false, 50, 50);
7084 mSecondWindow->assertNoEvents();
7085
7086 // Move to another window.
7087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7088 injectMotionEvent(mDispatcher,
7089 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7090 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7091 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7092 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7093 .x(150)
7094 .y(50))
7095 .build()))
7096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7097 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7098 mWindow->consumeDragEvent(true, 150, 50);
7099 mSecondWindow->consumeDragEvent(false, 50, 50);
7100
7101 // drop to another window.
7102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7103 injectMotionEvent(mDispatcher,
7104 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
7105 .buttonState(0)
7106 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7107 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7108 .x(150)
7109 .y(50))
7110 .build()))
7111 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7112 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7113 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7114 mWindow->assertNoEvents();
7115 mSecondWindow->assertNoEvents();
7116}
7117
Vishnu Nair062a8672021-09-03 16:07:44 -07007118class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
7119
7120TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
7121 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007122 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7123 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007124 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007125 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7126 window->setFocusable(true);
7127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7128 setFocusedWindow(window);
7129 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7130
7131 // With the flag set, window should not get any input
7132 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7133 mDispatcher->notifyKey(&keyArgs);
7134 window->assertNoEvents();
7135
7136 NotifyMotionArgs motionArgs =
7137 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7138 ADISPLAY_ID_DEFAULT);
7139 mDispatcher->notifyMotion(&motionArgs);
7140 window->assertNoEvents();
7141
7142 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007143 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7145
7146 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7147 mDispatcher->notifyKey(&keyArgs);
7148 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7149
7150 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7151 ADISPLAY_ID_DEFAULT);
7152 mDispatcher->notifyMotion(&motionArgs);
7153 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7154 window->assertNoEvents();
7155}
7156
7157TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
7158 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7159 std::make_shared<FakeApplicationHandle>();
7160 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007161 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7162 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007163 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7164 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007165 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007166 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007167 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7168 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007169 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007170 window->setOwnerInfo(222, 222);
7171 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7172 window->setFocusable(true);
7173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7174 setFocusedWindow(window);
7175 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7176
7177 // With the flag set, window should not get any input
7178 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7179 mDispatcher->notifyKey(&keyArgs);
7180 window->assertNoEvents();
7181
7182 NotifyMotionArgs motionArgs =
7183 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7184 ADISPLAY_ID_DEFAULT);
7185 mDispatcher->notifyMotion(&motionArgs);
7186 window->assertNoEvents();
7187
7188 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007189 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7191
7192 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7193 mDispatcher->notifyKey(&keyArgs);
7194 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7195
7196 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7197 ADISPLAY_ID_DEFAULT);
7198 mDispatcher->notifyMotion(&motionArgs);
7199 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
7200 window->assertNoEvents();
7201}
7202
7203TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
7204 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7205 std::make_shared<FakeApplicationHandle>();
7206 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007207 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7208 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007209 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7210 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007211 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007213 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7214 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007215 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007216 window->setOwnerInfo(222, 222);
7217 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7218 window->setFocusable(true);
7219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7220 setFocusedWindow(window);
7221 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7222
7223 // With the flag set, window should not get any input
7224 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7225 mDispatcher->notifyKey(&keyArgs);
7226 window->assertNoEvents();
7227
7228 NotifyMotionArgs motionArgs =
7229 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7230 ADISPLAY_ID_DEFAULT);
7231 mDispatcher->notifyMotion(&motionArgs);
7232 window->assertNoEvents();
7233
7234 // When the window is no longer obscured because it went on top, it should get input
7235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7236
7237 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7238 mDispatcher->notifyKey(&keyArgs);
7239 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7240
7241 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7242 ADISPLAY_ID_DEFAULT);
7243 mDispatcher->notifyMotion(&motionArgs);
7244 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7245 window->assertNoEvents();
7246}
7247
Antonio Kantekf16f2832021-09-28 04:39:20 +00007248class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7249protected:
7250 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007251 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007252 sp<FakeWindowHandle> mWindow;
7253 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007254 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007255
7256 void SetUp() override {
7257 InputDispatcherTest::SetUp();
7258
7259 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007260 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007261 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007262 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007263 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007264 mSecondWindow =
7265 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007266 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007267 mThirdWindow =
7268 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7269 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7270 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007271
7272 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7274 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7275 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007276 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007277
Antonio Kantek15beb512022-06-13 22:35:41 +00007278 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007279 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00007280 WINDOW_UID, true /* hasPermission */,
7281 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007282 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7283 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007284 mThirdWindow->assertNoEvents();
7285 }
7286
7287 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7288 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
7289 SECONDARY_WINDOW_UID, true /* hasPermission */,
7290 SECOND_DISPLAY_ID)) {
7291 mWindow->assertNoEvents();
7292 mSecondWindow->assertNoEvents();
7293 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007294 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007295 }
7296
Antonio Kantek15beb512022-06-13 22:35:41 +00007297 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7298 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007299 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7300 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007301 mWindow->consumeTouchModeEvent(inTouchMode);
7302 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007303 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007304 }
7305};
7306
Antonio Kantek26defcf2022-02-08 01:12:27 +00007307TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007308 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007309 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7310 windowInfo.ownerPid, windowInfo.ownerUid,
7311 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007312}
7313
Antonio Kantek26defcf2022-02-08 01:12:27 +00007314TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7315 const WindowInfo& windowInfo = *mWindow->getInfo();
7316 int32_t ownerPid = windowInfo.ownerPid;
7317 int32_t ownerUid = windowInfo.ownerUid;
7318 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7319 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007320 ownerUid, false /*hasPermission*/,
7321 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007322 mWindow->assertNoEvents();
7323 mSecondWindow->assertNoEvents();
7324}
7325
7326TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7327 const WindowInfo& windowInfo = *mWindow->getInfo();
7328 int32_t ownerPid = windowInfo.ownerPid;
7329 int32_t ownerUid = windowInfo.ownerUid;
7330 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007331 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
7332 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007333}
7334
Antonio Kantekf16f2832021-09-28 04:39:20 +00007335TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007336 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007337 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7338 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007339 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007340 mWindow->assertNoEvents();
7341 mSecondWindow->assertNoEvents();
7342}
7343
Antonio Kantek15beb512022-06-13 22:35:41 +00007344TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7345 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7346 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7347 windowInfo.ownerPid, windowInfo.ownerUid,
7348 true /*hasPermission*/, SECOND_DISPLAY_ID));
7349 mWindow->assertNoEvents();
7350 mSecondWindow->assertNoEvents();
7351 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7352}
7353
Antonio Kantek48710e42022-03-24 14:19:30 -07007354TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7355 // Interact with the window first.
7356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7358 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7359
7360 // Then remove focus.
7361 mWindow->setFocusable(false);
7362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7363
7364 // Assert that caller can switch touch mode by owning one of the last interacted window.
7365 const WindowInfo& windowInfo = *mWindow->getInfo();
7366 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7367 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007368 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007369}
7370
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007371class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7372public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007373 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007374 std::shared_ptr<FakeApplicationHandle> application =
7375 std::make_shared<FakeApplicationHandle>();
7376 std::string name = "Fake Spy ";
7377 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007378 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7379 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007380 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007381 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007382 return spy;
7383 }
7384
7385 sp<FakeWindowHandle> createForeground() {
7386 std::shared_ptr<FakeApplicationHandle> application =
7387 std::make_shared<FakeApplicationHandle>();
7388 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007389 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7390 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007391 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007392 return window;
7393 }
7394
7395private:
7396 int mSpyCount{0};
7397};
7398
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007399using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007400/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007401 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7402 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007403TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7404 ScopedSilentDeath _silentDeath;
7405
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007406 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007407 spy->setTrustedOverlay(false);
7408 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7409 ".* not a trusted overlay");
7410}
7411
7412/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007413 * Input injection into a display with a spy window but no foreground windows should succeed.
7414 */
7415TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007416 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7418
7419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7420 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7421 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7422 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7423}
7424
7425/**
7426 * Verify the order in which different input windows receive events. The touched foreground window
7427 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7428 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7429 * receive events before ones belows it.
7430 *
7431 * Here, we set up a scenario with four windows in the following Z order from the top:
7432 * spy1, spy2, window, spy3.
7433 * We then inject an event and verify that the foreground "window" receives it first, followed by
7434 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7435 * window.
7436 */
7437TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7438 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007439 auto spy1 = createSpy();
7440 auto spy2 = createSpy();
7441 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7443 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7444 const size_t numChannels = channels.size();
7445
Michael Wright8e9a8562022-02-09 13:44:29 +00007446 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007447 if (!epollFd.ok()) {
7448 FAIL() << "Failed to create epoll fd";
7449 }
7450
7451 for (size_t i = 0; i < numChannels; i++) {
7452 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7453 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7454 FAIL() << "Failed to add fd to epoll";
7455 }
7456 }
7457
7458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7459 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7461
7462 std::vector<size_t> eventOrder;
7463 std::vector<struct epoll_event> events(numChannels);
7464 for (;;) {
7465 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7466 (100ms).count());
7467 if (nFds < 0) {
7468 FAIL() << "Failed to call epoll_wait";
7469 }
7470 if (nFds == 0) {
7471 break; // epoll_wait timed out
7472 }
7473 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007474 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007475 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007476 channels[i]->consumeMotionDown();
7477 }
7478 }
7479
7480 // Verify the order in which the events were received.
7481 EXPECT_EQ(3u, eventOrder.size());
7482 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7483 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7484 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7485}
7486
7487/**
7488 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7489 */
7490TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7491 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007492 auto spy = createSpy();
7493 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7495
7496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7497 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7499 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7500 spy->assertNoEvents();
7501}
7502
7503/**
7504 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7505 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7506 * to the window.
7507 */
7508TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7509 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007510 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007511 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7513
7514 // Inject an event outside the spy window's touchable region.
7515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7518 window->consumeMotionDown();
7519 spy->assertNoEvents();
7520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7521 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7522 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7523 window->consumeMotionUp();
7524 spy->assertNoEvents();
7525
7526 // Inject an event inside the spy window's touchable region.
7527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7528 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7529 {5, 10}))
7530 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7531 window->consumeMotionDown();
7532 spy->consumeMotionDown();
7533}
7534
7535/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007536 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007537 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007538 */
7539TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7540 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007541 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007542 auto spy = createSpy();
7543 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007544 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007545 spy->setFrame(Rect{0, 0, 20, 20});
7546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7547
7548 // Inject an event outside the spy window's frame and touchable region.
7549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007550 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7551 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7553 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007554 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007555}
7556
7557/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007558 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7559 * pointers that are down within its bounds.
7560 */
7561TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7562 auto windowLeft = createForeground();
7563 windowLeft->setFrame({0, 0, 100, 200});
7564 auto windowRight = createForeground();
7565 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007566 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007567 spy->setFrame({0, 0, 200, 200});
7568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
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 windowLeft->consumeMotionDown();
7575 spy->consumeMotionDown();
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 windowRight->consumeMotionDown();
7589 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7590}
7591
7592/**
7593 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7594 * the spy should receive the second pointer with ACTION_DOWN.
7595 */
7596TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7597 auto window = createForeground();
7598 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007599 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007600 spyRight->setFrame({100, 0, 200, 200});
7601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7602
7603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7604 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7605 {50, 50}))
7606 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7607 window->consumeMotionDown();
7608 spyRight->assertNoEvents();
7609
7610 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007611 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007612 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7613 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7614 .pointer(
7615 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7616 .build();
7617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7618 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7619 InputEventInjectionSync::WAIT_FOR_RESULT))
7620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7621 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7622 spyRight->consumeMotionDown();
7623}
7624
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007625/**
7626 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7627 * windows should be allowed to control split touch.
7628 */
7629TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007630 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007631 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007632 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007633 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007634
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007635 auto window = createForeground();
7636 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007637
7638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7639
7640 // First finger down, no window touched.
7641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7642 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7643 {100, 200}))
7644 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7645 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7646 window->assertNoEvents();
7647
7648 // Second finger down on window, the window should receive touch down.
7649 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007650 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007651 .displayId(ADISPLAY_ID_DEFAULT)
7652 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7653 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7654 .x(100)
7655 .y(200))
7656 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7657 .build();
7658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7659 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7660 InputEventInjectionSync::WAIT_FOR_RESULT))
7661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7662
7663 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7664 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7665}
7666
7667/**
7668 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7669 * do not receive key events.
7670 */
7671TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007672 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007673 spy->setFocusable(false);
7674
7675 auto window = createForeground();
7676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7677 setFocusedWindow(window);
7678 window->consumeFocusEvent(true);
7679
7680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7681 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7682 window->consumeKeyDown(ADISPLAY_ID_NONE);
7683
7684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7685 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7686 window->consumeKeyUp(ADISPLAY_ID_NONE);
7687
7688 spy->assertNoEvents();
7689}
7690
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007691using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7692
7693/**
7694 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7695 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7696 */
7697TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7698 auto window = createForeground();
7699 auto spy1 = createSpy();
7700 auto spy2 = createSpy();
7701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7702
7703 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7704 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7705 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7706 window->consumeMotionDown();
7707 spy1->consumeMotionDown();
7708 spy2->consumeMotionDown();
7709
7710 // Pilfer pointers from the second spy window.
7711 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7712 spy2->assertNoEvents();
7713 spy1->consumeMotionCancel();
7714 window->consumeMotionCancel();
7715
7716 // The rest of the gesture should only be sent to the second spy window.
7717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7718 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7719 ADISPLAY_ID_DEFAULT))
7720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7721 spy2->consumeMotionMove();
7722 spy1->assertNoEvents();
7723 window->assertNoEvents();
7724}
7725
7726/**
7727 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7728 * in the middle of the gesture.
7729 */
7730TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7731 auto window = createForeground();
7732 auto spy = createSpy();
7733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7734
7735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7736 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7738 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7739 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7740
7741 window->releaseChannel();
7742
7743 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7744
7745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7746 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7747 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7748 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7749}
7750
7751/**
7752 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7753 * the spy, but not to any other windows.
7754 */
7755TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7756 auto spy = createSpy();
7757 auto window = createForeground();
7758
7759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7760
7761 // First finger down on the window and the spy.
7762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7763 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7764 {100, 200}))
7765 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7766 spy->consumeMotionDown();
7767 window->consumeMotionDown();
7768
7769 // Spy window pilfers the pointers.
7770 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7771 window->consumeMotionCancel();
7772
7773 // Second finger down on the window and spy, but the window should not receive the pointer down.
7774 const MotionEvent secondFingerDownEvent =
7775 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7776 .displayId(ADISPLAY_ID_DEFAULT)
7777 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7778 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7779 .x(100)
7780 .y(200))
7781 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7782 .build();
7783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7784 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7785 InputEventInjectionSync::WAIT_FOR_RESULT))
7786 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7787
7788 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7789
7790 // Third finger goes down outside all windows, so injection should fail.
7791 const MotionEvent thirdFingerDownEvent =
7792 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7793 .displayId(ADISPLAY_ID_DEFAULT)
7794 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7795 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7796 .x(100)
7797 .y(200))
7798 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7799 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7800 .build();
7801 ASSERT_EQ(InputEventInjectionResult::FAILED,
7802 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7803 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08007804 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007805
7806 spy->assertNoEvents();
7807 window->assertNoEvents();
7808}
7809
7810/**
7811 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7812 */
7813TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7814 auto spy = createSpy();
7815 spy->setFrame(Rect(0, 0, 100, 100));
7816 auto window = createForeground();
7817 window->setFrame(Rect(0, 0, 200, 200));
7818
7819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7820
7821 // First finger down on the window only
7822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7823 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7824 {150, 150}))
7825 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7826 window->consumeMotionDown();
7827
7828 // Second finger down on the spy and window
7829 const MotionEvent secondFingerDownEvent =
7830 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7831 .displayId(ADISPLAY_ID_DEFAULT)
7832 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7833 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7834 .x(150)
7835 .y(150))
7836 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7837 .build();
7838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7839 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7840 InputEventInjectionSync::WAIT_FOR_RESULT))
7841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7842 spy->consumeMotionDown();
7843 window->consumeMotionPointerDown(1);
7844
7845 // Third finger down on the spy and window
7846 const MotionEvent thirdFingerDownEvent =
7847 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7848 .displayId(ADISPLAY_ID_DEFAULT)
7849 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7850 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7851 .x(150)
7852 .y(150))
7853 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7854 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7855 .build();
7856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7857 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7858 InputEventInjectionSync::WAIT_FOR_RESULT))
7859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7860 spy->consumeMotionPointerDown(1);
7861 window->consumeMotionPointerDown(2);
7862
7863 // Spy window pilfers the pointers.
7864 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7865 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7866 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7867
7868 spy->assertNoEvents();
7869 window->assertNoEvents();
7870}
7871
7872/**
7873 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7874 * other windows should be canceled. If this results in the cancellation of all pointers for some
7875 * window, then that window should receive ACTION_CANCEL.
7876 */
7877TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7878 auto spy = createSpy();
7879 spy->setFrame(Rect(0, 0, 100, 100));
7880 auto window = createForeground();
7881 window->setFrame(Rect(0, 0, 200, 200));
7882
7883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7884
7885 // First finger down on both spy and window
7886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7887 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7888 {10, 10}))
7889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7890 window->consumeMotionDown();
7891 spy->consumeMotionDown();
7892
7893 // Second finger down on the spy and window
7894 const MotionEvent secondFingerDownEvent =
7895 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7896 .displayId(ADISPLAY_ID_DEFAULT)
7897 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7898 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7899 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7900 .build();
7901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7902 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7903 InputEventInjectionSync::WAIT_FOR_RESULT))
7904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7905 spy->consumeMotionPointerDown(1);
7906 window->consumeMotionPointerDown(1);
7907
7908 // Spy window pilfers the pointers.
7909 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7910 window->consumeMotionCancel();
7911
7912 spy->assertNoEvents();
7913 window->assertNoEvents();
7914}
7915
7916/**
7917 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7918 * be sent to other windows
7919 */
7920TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7921 auto spy = createSpy();
7922 spy->setFrame(Rect(0, 0, 100, 100));
7923 auto window = createForeground();
7924 window->setFrame(Rect(0, 0, 200, 200));
7925
7926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7927
7928 // First finger down on both window and spy
7929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7930 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7931 {10, 10}))
7932 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7933 window->consumeMotionDown();
7934 spy->consumeMotionDown();
7935
7936 // Spy window pilfers the pointers.
7937 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7938 window->consumeMotionCancel();
7939
7940 // Second finger down on the window only
7941 const MotionEvent secondFingerDownEvent =
7942 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7943 .displayId(ADISPLAY_ID_DEFAULT)
7944 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7945 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7946 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7947 .x(150)
7948 .y(150))
7949 .build();
7950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7951 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7952 InputEventInjectionSync::WAIT_FOR_RESULT))
7953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7954 window->consumeMotionDown();
7955 window->assertNoEvents();
7956
7957 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7958 spy->consumeMotionMove();
7959 spy->assertNoEvents();
7960}
7961
Prabir Pradhand65552b2021-10-07 11:23:50 -07007962class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7963public:
7964 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7965 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7966 std::make_shared<FakeApplicationHandle>();
7967 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007968 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7969 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007970 overlay->setFocusable(false);
7971 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007972 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007973 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007974 overlay->setTrustedOverlay(true);
7975
7976 std::shared_ptr<FakeApplicationHandle> application =
7977 std::make_shared<FakeApplicationHandle>();
7978 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007979 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7980 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007981 window->setFocusable(true);
7982 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007983
7984 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7986 setFocusedWindow(window);
7987 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7988 return {std::move(overlay), std::move(window)};
7989 }
7990
7991 void sendFingerEvent(int32_t action) {
7992 NotifyMotionArgs motionArgs =
7993 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7994 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7995 mDispatcher->notifyMotion(&motionArgs);
7996 }
7997
7998 void sendStylusEvent(int32_t action) {
7999 NotifyMotionArgs motionArgs =
8000 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8001 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
8002 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
8003 mDispatcher->notifyMotion(&motionArgs);
8004 }
8005};
8006
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008007using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
8008
8009TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
8010 ScopedSilentDeath _silentDeath;
8011
Prabir Pradhand65552b2021-10-07 11:23:50 -07008012 auto [overlay, window] = setupStylusOverlayScenario();
8013 overlay->setTrustedOverlay(false);
8014 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
8015 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
8016 ".* not a trusted overlay");
8017}
8018
8019TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
8020 auto [overlay, window] = setupStylusOverlayScenario();
8021 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8022
8023 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8024 overlay->consumeMotionDown();
8025 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8026 overlay->consumeMotionUp();
8027
8028 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8029 window->consumeMotionDown();
8030 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8031 window->consumeMotionUp();
8032
8033 overlay->assertNoEvents();
8034 window->assertNoEvents();
8035}
8036
8037TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
8038 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008039 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8041
8042 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8043 overlay->consumeMotionDown();
8044 window->consumeMotionDown();
8045 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8046 overlay->consumeMotionUp();
8047 window->consumeMotionUp();
8048
8049 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8050 window->consumeMotionDown();
8051 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8052 window->consumeMotionUp();
8053
8054 overlay->assertNoEvents();
8055 window->assertNoEvents();
8056}
8057
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00008058/**
8059 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
8060 * The scenario is as follows:
8061 * - The stylus interceptor overlay is configured as a spy window.
8062 * - The stylus interceptor spy receives the start of a new stylus gesture.
8063 * - It pilfers pointers and then configures itself to no longer be a spy.
8064 * - The stylus interceptor continues to receive the rest of the gesture.
8065 */
8066TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
8067 auto [overlay, window] = setupStylusOverlayScenario();
8068 overlay->setSpy(true);
8069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8070
8071 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8072 overlay->consumeMotionDown();
8073 window->consumeMotionDown();
8074
8075 // The interceptor pilfers the pointers.
8076 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
8077 window->consumeMotionCancel();
8078
8079 // The interceptor configures itself so that it is no longer a spy.
8080 overlay->setSpy(false);
8081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8082
8083 // It continues to receive the rest of the stylus gesture.
8084 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
8085 overlay->consumeMotionMove();
8086 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8087 overlay->consumeMotionUp();
8088
8089 window->assertNoEvents();
8090}
8091
Prabir Pradhan5735a322022-04-11 17:23:34 +00008092struct User {
8093 int32_t mPid;
8094 int32_t mUid;
8095 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
8096 std::unique_ptr<InputDispatcher>& mDispatcher;
8097
8098 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
8099 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
8100
8101 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
8102 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
8103 ADISPLAY_ID_DEFAULT, {100, 200},
8104 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
8105 AMOTION_EVENT_INVALID_CURSOR_POSITION},
8106 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
8107 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
8108 }
8109
8110 InputEventInjectionResult injectTargetedKey(int32_t action) const {
8111 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
8112 InputEventInjectionSync::WAIT_FOR_RESULT,
8113 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
8114 mPolicyFlags);
8115 }
8116
8117 sp<FakeWindowHandle> createWindow() const {
8118 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8119 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008120 sp<FakeWindowHandle> window =
8121 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
8122 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00008123 window->setOwnerInfo(mPid, mUid);
8124 return window;
8125 }
8126};
8127
8128using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
8129
8130TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
8131 auto owner = User(mDispatcher, 10, 11);
8132 auto window = owner.createWindow();
8133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8134
8135 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8136 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8137 window->consumeMotionDown();
8138
8139 setFocusedWindow(window);
8140 window->consumeFocusEvent(true);
8141
8142 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8143 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8144 window->consumeKeyDown(ADISPLAY_ID_NONE);
8145}
8146
8147TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
8148 auto owner = User(mDispatcher, 10, 11);
8149 auto window = owner.createWindow();
8150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8151
8152 auto rando = User(mDispatcher, 20, 21);
8153 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8154 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8155
8156 setFocusedWindow(window);
8157 window->consumeFocusEvent(true);
8158
8159 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8160 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8161 window->assertNoEvents();
8162}
8163
8164TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
8165 auto owner = User(mDispatcher, 10, 11);
8166 auto window = owner.createWindow();
8167 auto spy = owner.createWindow();
8168 spy->setSpy(true);
8169 spy->setTrustedOverlay(true);
8170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8171
8172 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8173 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8174 spy->consumeMotionDown();
8175 window->consumeMotionDown();
8176}
8177
8178TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
8179 auto owner = User(mDispatcher, 10, 11);
8180 auto window = owner.createWindow();
8181
8182 auto rando = User(mDispatcher, 20, 21);
8183 auto randosSpy = rando.createWindow();
8184 randosSpy->setSpy(true);
8185 randosSpy->setTrustedOverlay(true);
8186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8187
8188 // The event is targeted at owner's window, so injection should succeed, but the spy should
8189 // not receive the event.
8190 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8191 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8192 randosSpy->assertNoEvents();
8193 window->consumeMotionDown();
8194}
8195
8196TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
8197 auto owner = User(mDispatcher, 10, 11);
8198 auto window = owner.createWindow();
8199
8200 auto rando = User(mDispatcher, 20, 21);
8201 auto randosSpy = rando.createWindow();
8202 randosSpy->setSpy(true);
8203 randosSpy->setTrustedOverlay(true);
8204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8205
8206 // A user that has injection permission can inject into any window.
8207 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8208 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8209 ADISPLAY_ID_DEFAULT));
8210 randosSpy->consumeMotionDown();
8211 window->consumeMotionDown();
8212
8213 setFocusedWindow(randosSpy);
8214 randosSpy->consumeFocusEvent(true);
8215
8216 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
8217 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
8218 window->assertNoEvents();
8219}
8220
8221TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
8222 auto owner = User(mDispatcher, 10, 11);
8223 auto window = owner.createWindow();
8224
8225 auto rando = User(mDispatcher, 20, 21);
8226 auto randosWindow = rando.createWindow();
8227 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8228 randosWindow->setWatchOutsideTouch(true);
8229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8230
8231 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8232 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8233 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8234 window->consumeMotionDown();
8235 randosWindow->consumeMotionOutside();
8236}
8237
Garfield Tane84e6f92019-08-29 17:28:41 -07008238} // namespace android::inputdispatcher