blob: 711366dd5da72688f2a253b7d7b597d5aef0aa12 [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;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -080055static constexpr int32_t SECOND_DEVICE_ID = 2;
Michael Wrightd02c5b62014-02-10 15:10:22 -080056
Jeff Brownf086ddb2014-02-11 14:28:48 -080057// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000058static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
59static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080060
Siarhei Vishniakouf372b812023-02-14 18:06:51 -080061static constexpr int32_t ACTION_DOWN = AMOTION_EVENT_ACTION_DOWN;
62static constexpr int32_t ACTION_MOVE = AMOTION_EVENT_ACTION_MOVE;
63static constexpr int32_t ACTION_UP = AMOTION_EVENT_ACTION_UP;
64static constexpr int32_t ACTION_HOVER_ENTER = AMOTION_EVENT_ACTION_HOVER_ENTER;
65static constexpr int32_t ACTION_HOVER_EXIT = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080066static constexpr int32_t ACTION_OUTSIDE = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -080067static constexpr int32_t ACTION_CANCEL = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -080068/**
69 * The POINTER_DOWN(0) is an unusual, but valid, action. It just means that the new pointer in the
70 * MotionEvent is at the index 0 rather than 1 (or later). That is, the pointer id=0 (which is at
71 * index 0) is the new pointer going down. The same pointer could have been placed at a different
72 * index, and the action would become POINTER_1_DOWN, 2, etc..; these would all be valid. In
73 * general, we try to place pointer id = 0 at the index 0. Of course, this is not possible if
74 * pointer id=0 leaves but the pointer id=1 remains.
75 */
76static constexpr int32_t POINTER_0_DOWN =
77 AMOTION_EVENT_ACTION_POINTER_DOWN | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080078static constexpr int32_t POINTER_1_DOWN =
79 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000080static constexpr int32_t POINTER_2_DOWN =
81 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000082static constexpr int32_t POINTER_3_DOWN =
83 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Arthur Hungc539dbb2022-12-08 07:45:36 +000084static constexpr int32_t POINTER_0_UP =
85 AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080086static constexpr int32_t POINTER_1_UP =
87 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
88
Antonio Kantek15beb512022-06-13 22:35:41 +000089// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000090static constexpr int32_t WINDOW_PID = 999;
91static constexpr int32_t WINDOW_UID = 1001;
92
Antonio Kantek15beb512022-06-13 22:35:41 +000093// The default pid and uid for the windows created on the secondary display by the test.
94static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
95static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
96
Prabir Pradhan5735a322022-04-11 17:23:34 +000097// The default policy flags to use for event injection by tests.
98static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +0000100// An arbitrary pid of the gesture monitor window
101static constexpr int32_t MONITOR_PID = 2001;
102
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800103static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
104
Arthur Hungc539dbb2022-12-08 07:45:36 +0000105static constexpr int expectedWallpaperFlags =
106 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
107
chaviwd1c23182019-12-20 18:44:56 -0800108struct PointF {
109 float x;
110 float y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800111 auto operator<=>(const PointF&) const = default;
chaviwd1c23182019-12-20 18:44:56 -0800112};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113
Gang Wang342c9272020-01-13 13:15:04 -0500114/**
115 * Return a DOWN key event with KEYCODE_A.
116 */
117static KeyEvent getTestKeyEvent() {
118 KeyEvent event;
119
Garfield Tanfbe732e2020-01-24 11:26:14 -0800120 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
121 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
122 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -0500123 return event;
124}
125
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000126static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
127 ASSERT_EQ(expectedAction, receivedAction)
128 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
129 << MotionEvent::actionToString(receivedAction);
130}
131
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800132MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
133 bool matches = action == arg.getAction();
134 if (!matches) {
135 *result_listener << "expected action " << MotionEvent::actionToString(action)
136 << ", but got " << MotionEvent::actionToString(arg.getAction());
137 }
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800138 if (action == AMOTION_EVENT_ACTION_DOWN) {
139 if (!matches) {
140 *result_listener << "; ";
141 }
142 *result_listener << "downTime should match eventTime for ACTION_DOWN events";
143 matches &= arg.getDownTime() == arg.getEventTime();
144 }
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800145 if (action == AMOTION_EVENT_ACTION_CANCEL) {
146 if (!matches) {
147 *result_listener << "; ";
148 }
149 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
150 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
151 }
152 return matches;
153}
154
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800155MATCHER_P(WithDownTime, downTime, "InputEvent with specified downTime") {
156 return arg.getDownTime() == downTime;
157}
158
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800159MATCHER_P(WithDisplayId, displayId, "InputEvent with specified displayId") {
160 return arg.getDisplayId() == displayId;
161}
162
Siarhei Vishniakouf372b812023-02-14 18:06:51 -0800163MATCHER_P(WithDeviceId, deviceId, "InputEvent with specified deviceId") {
164 return arg.getDeviceId() == deviceId;
165}
166
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800167MATCHER_P(WithSource, source, "InputEvent with specified source") {
168 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
169 << inputEventSourceToString(arg.getSource());
170 return arg.getSource() == source;
171}
172
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800173MATCHER_P(WithFlags, flags, "InputEvent with specified flags") {
174 return arg.getFlags() == flags;
175}
176
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800177MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
178 if (arg.getPointerCount() != 1) {
179 *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
180 return false;
181 }
Harry Cutts33476232023-01-30 19:57:29 +0000182 return arg.getX(/*pointerIndex=*/0) == x && arg.getY(/*pointerIndex=*/0) == y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800183}
184
Siarhei Vishniakouf372b812023-02-14 18:06:51 -0800185MATCHER_P(WithPointerCount, pointerCount, "MotionEvent with specified number of pointers") {
186 return arg.getPointerCount() == pointerCount;
187}
188
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800189MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
190 // Build a map for the received pointers, by pointer id
191 std::map<int32_t /*pointerId*/, PointF> actualPointers;
192 for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
193 const int32_t pointerId = arg.getPointerId(pointerIndex);
194 actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
195 }
196 return pointers == actualPointers;
197}
198
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199// --- FakeInputDispatcherPolicy ---
200
201class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
202 InputDispatcherConfiguration mConfig;
203
Prabir Pradhanedd96402022-02-15 01:46:16 -0800204 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
205
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000207 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208
209public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000210 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800211
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800212 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700213 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
214 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
215 EXPECT_EQ(event.getDisplayId(), args.displayId);
216
217 const auto& keyEvent = static_cast<const KeyEvent&>(event);
218 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
219 EXPECT_EQ(keyEvent.getAction(), args.action);
220 });
Jackal Guof9696682018-10-05 12:23:23 +0800221 }
222
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700223 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
224 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
225 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
226 EXPECT_EQ(event.getDisplayId(), args.displayId);
227
228 const auto& motionEvent = static_cast<const MotionEvent&>(event);
229 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
230 EXPECT_EQ(motionEvent.getAction(), args.action);
231 EXPECT_EQ(motionEvent.getX(0), point.x);
232 EXPECT_EQ(motionEvent.getY(0), point.y);
233 EXPECT_EQ(motionEvent.getRawX(0), point.x);
234 EXPECT_EQ(motionEvent.getRawY(0), point.y);
235 });
Jackal Guof9696682018-10-05 12:23:23 +0800236 }
237
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700238 void assertFilterInputEventWasNotCalled() {
239 std::scoped_lock lock(mLock);
240 ASSERT_EQ(nullptr, mFilteredEvent);
241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800243 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700244 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800245 ASSERT_TRUE(mConfigurationChangedTime)
246 << "Timed out waiting for configuration changed call";
247 ASSERT_EQ(*mConfigurationChangedTime, when);
248 mConfigurationChangedTime = std::nullopt;
249 }
250
251 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700252 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800253 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800254 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800255 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
256 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
257 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
258 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
259 mLastNotifySwitch = std::nullopt;
260 }
261
chaviwfd6d3512019-03-25 13:23:49 -0700262 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700263 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800264 ASSERT_EQ(touchedToken, mOnPointerDownToken);
265 mOnPointerDownToken.clear();
266 }
267
268 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700269 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800270 ASSERT_TRUE(mOnPointerDownToken == nullptr)
271 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700272 }
273
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700274 // This function must be called soon after the expected ANR timer starts,
275 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500276 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700277 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500278 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800279 std::unique_lock lock(mLock);
280 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500281 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800282 ASSERT_NO_FATAL_FAILURE(
283 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500284 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700285 }
286
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000287 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800288 const sp<WindowInfoHandle>& window) {
289 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
290 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
291 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500292 }
293
Prabir Pradhanedd96402022-02-15 01:46:16 -0800294 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
295 const sp<IBinder>& expectedToken,
296 int32_t expectedPid) {
297 std::unique_lock lock(mLock);
298 android::base::ScopedLockAssertion assumeLocked(mLock);
299 AnrResult result;
300 ASSERT_NO_FATAL_FAILURE(result =
301 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
302 const auto& [token, pid] = result;
303 ASSERT_EQ(expectedToken, token);
304 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500305 }
306
Prabir Pradhanedd96402022-02-15 01:46:16 -0800307 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000308 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500309 std::unique_lock lock(mLock);
310 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800311 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
312 const auto& [token, _] = result;
313 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000314 }
315
Prabir Pradhanedd96402022-02-15 01:46:16 -0800316 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
317 int32_t expectedPid) {
318 std::unique_lock lock(mLock);
319 android::base::ScopedLockAssertion assumeLocked(mLock);
320 AnrResult result;
321 ASSERT_NO_FATAL_FAILURE(
322 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
323 const auto& [token, pid] = result;
324 ASSERT_EQ(expectedToken, token);
325 ASSERT_EQ(expectedPid, pid);
326 }
327
328 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000329 sp<IBinder> getResponsiveWindowToken() {
330 std::unique_lock lock(mLock);
331 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800332 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
333 const auto& [token, _] = result;
334 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700335 }
336
337 void assertNotifyAnrWasNotCalled() {
338 std::scoped_lock lock(mLock);
339 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800340 ASSERT_TRUE(mAnrWindows.empty());
341 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500342 << "ANR was not called, but please also consume the 'connection is responsive' "
343 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700344 }
345
Garfield Tan1c7bc862020-01-28 13:24:04 -0800346 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
347 mConfig.keyRepeatTimeout = timeout;
348 mConfig.keyRepeatDelay = delay;
349 }
350
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000351 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800352 std::unique_lock lock(mLock);
353 base::ScopedLockAssertion assumeLocked(mLock);
354
355 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
356 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000357 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800358 enabled;
359 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000360 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
361 << ") to be called.";
362 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800363 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000364 auto request = *mPointerCaptureRequest;
365 mPointerCaptureRequest.reset();
366 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800367 }
368
369 void assertSetPointerCaptureNotCalled() {
370 std::unique_lock lock(mLock);
371 base::ScopedLockAssertion assumeLocked(mLock);
372
373 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000374 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800375 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000376 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800377 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000378 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800379 }
380
arthurhungf452d0b2021-01-06 00:19:52 +0800381 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
382 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800383 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800384 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800385 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800386 }
387
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800388 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
389 std::unique_lock lock(mLock);
390 base::ScopedLockAssertion assumeLocked(mLock);
391 std::optional<sp<IBinder>> receivedToken =
392 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
393 mNotifyInputChannelBroken);
394 ASSERT_TRUE(receivedToken.has_value());
395 ASSERT_EQ(token, *receivedToken);
396 }
397
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800398 /**
399 * Set policy timeout. A value of zero means next key will not be intercepted.
400 */
401 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
402 mInterceptKeyTimeout = timeout;
403 }
404
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700406 std::mutex mLock;
407 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
408 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
409 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
410 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800411
Prabir Pradhan99987712020-11-10 18:43:05 -0800412 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000413
414 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800415
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700416 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700417 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800418 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
419 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700420 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800421 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
422 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700423
arthurhungf452d0b2021-01-06 00:19:52 +0800424 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800425 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800426
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800427 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
428
Prabir Pradhanedd96402022-02-15 01:46:16 -0800429 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
430 // for a specific container to become non-empty. When the container is non-empty, return the
431 // first entry from the container and erase it.
432 template <class T>
433 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
434 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
435 // If there is an ANR, Dispatcher won't be idle because there are still events
436 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
437 // before checking if ANR was called.
438 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
439 // to provide it some time to act. 100ms seems reasonable.
440 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
441 const std::chrono::time_point start = std::chrono::steady_clock::now();
442 std::optional<T> token =
443 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
444 if (!token.has_value()) {
445 ADD_FAILURE() << "Did not receive the ANR callback";
446 return {};
447 }
448
449 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
450 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
451 // the dispatcher started counting before this function was called
452 if (std::chrono::abs(timeout - waited) > 100ms) {
453 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
454 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
455 << "ms, but waited "
456 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
457 << "ms instead";
458 }
459 return *token;
460 }
461
462 template <class T>
463 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
464 std::queue<T>& storage,
465 std::unique_lock<std::mutex>& lock,
466 std::condition_variable& condition)
467 REQUIRES(mLock) {
468 condition.wait_for(lock, timeout,
469 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
470 if (storage.empty()) {
471 ADD_FAILURE() << "Did not receive the expected callback";
472 return std::nullopt;
473 }
474 T item = storage.front();
475 storage.pop();
476 return std::make_optional(item);
477 }
478
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600479 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700480 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800481 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 }
483
Prabir Pradhanedd96402022-02-15 01:46:16 -0800484 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
485 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700486 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800487 ASSERT_TRUE(pid.has_value());
488 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700489 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500490 }
491
Prabir Pradhanedd96402022-02-15 01:46:16 -0800492 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
493 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500494 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800495 ASSERT_TRUE(pid.has_value());
496 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500497 mNotifyAnr.notify_all();
498 }
499
500 void notifyNoFocusedWindowAnr(
501 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
502 std::scoped_lock lock(mLock);
503 mAnrApplications.push(applicationHandle);
504 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
506
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800507 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
508 std::scoped_lock lock(mLock);
509 mBrokenInputChannels.push(connectionToken);
510 mNotifyInputChannelBroken.notify_all();
511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600513 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700514
Chris Yef59a2f42020-10-16 12:55:26 -0700515 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
516 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
517 const std::vector<float>& values) override {}
518
519 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
520 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000521
Chris Yefb552902021-02-03 17:18:37 -0800522 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
523
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600524 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 *outConfig = mConfig;
526 }
527
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600528 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700529 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800530 switch (inputEvent->getType()) {
531 case AINPUT_EVENT_TYPE_KEY: {
532 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800533 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800534 break;
535 }
536
537 case AINPUT_EVENT_TYPE_MOTION: {
538 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800539 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800540 break;
541 }
542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 return true;
544 }
545
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800546 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
547 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
548 // Clear intercept state when we handled the event.
549 mInterceptKeyTimeout = 0ms;
550 }
551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600553 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600555 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800556 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
557 // Clear intercept state so we could dispatch the event in next wake.
558 mInterceptKeyTimeout = 0ms;
559 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
561
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600562 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 return false;
564 }
565
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600566 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
567 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700568 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800569 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
570 * essentially a passthrough for notifySwitch.
571 */
Harry Cutts33476232023-01-30 19:57:29 +0000572 mLastNotifySwitch = NotifySwitchArgs(/*id=*/1, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 }
574
Sean Stoutb4e0a592021-02-23 07:34:53 -0800575 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600577 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700578 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700579 mOnPointerDownToken = newToken;
580 }
581
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000582 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800583 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000584 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800585 mPointerCaptureChangedCondition.notify_all();
586 }
587
arthurhungf452d0b2021-01-06 00:19:52 +0800588 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
589 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800590 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800591 mDropTargetWindowToken = token;
592 }
593
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700594 void assertFilterInputEventWasCalledInternal(
595 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700596 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800597 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700598 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800599 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601};
602
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603// --- InputDispatcherTest ---
604
605class InputDispatcherTest : public testing::Test {
606protected:
607 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700608 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000610 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700611 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800612 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800613 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000614 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700615 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 }
617
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000618 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700619 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700621 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700623
624 /**
625 * Used for debugging when writing the test
626 */
627 void dumpDispatcherState() {
628 std::string dump;
629 mDispatcher->dump(dump);
630 std::stringstream ss(dump);
631 std::string to;
632
633 while (std::getline(ss, to, '\n')) {
634 ALOGE("%s", to.c_str());
635 }
636 }
Vishnu Nair958da932020-08-21 17:12:37 -0700637
chaviw3277faf2021-05-19 16:45:23 -0500638 void setFocusedWindow(const sp<WindowInfoHandle>& window,
639 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700640 FocusRequest request;
641 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000642 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700643 if (focusedWindow) {
644 request.focusedToken = focusedWindow->getToken();
645 }
646 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
647 request.displayId = window->getInfo()->displayId;
648 mDispatcher->setFocusedWindow(request);
649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650};
651
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
653 KeyEvent event;
654
655 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800656 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
657 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600658 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
659 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000661 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000662 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 << "Should reject key events with undefined action.";
664
665 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800666 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
667 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600668 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800669 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000670 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000671 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 << "Should reject key events with ACTION_MULTIPLE.";
673}
674
675TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
676 MotionEvent event;
677 PointerProperties pointerProperties[MAX_POINTERS + 1];
678 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800679 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 pointerProperties[i].clear();
681 pointerProperties[i].id = i;
682 pointerCoords[i].clear();
683 }
684
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800685 // Some constants commonly used below
686 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
687 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
688 constexpr int32_t metaState = AMETA_NONE;
689 constexpr MotionClassification classification = MotionClassification::NONE;
690
chaviw9eaa22c2020-07-01 16:21:27 -0700691 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800693 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700694 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
695 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700696 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
697 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700698 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800699 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000700 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000701 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 << "Should reject motion events with undefined action.";
703
704 // Rejects pointer down 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_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
707 identityTransform, 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,
Harry Cutts33476232023-01-30 19:57:29 +0000712 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000713 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 << "Should reject motion events with pointer down 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_DOWN |
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,
Harry Cutts33476232023-01-30 19:57:29 +0000724 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000725 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 << "Should reject motion events with pointer down index too small.";
727
728 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800729 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800730 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
731 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
732 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
733 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500734 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800735 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000736 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000737 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 << "Should reject motion events with pointer up index too large.";
739
Garfield Tanfbe732e2020-01-24 11:26:14 -0800740 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700741 AMOTION_EVENT_ACTION_POINTER_UP |
742 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700743 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
744 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700745 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500746 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800747 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000748 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000749 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 << "Should reject motion events with pointer up index too small.";
751
752 // Rejects motion events with invalid number of pointers.
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*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800759 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000760 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000761 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 << "Should reject motion events with 0 pointers.";
763
Garfield Tanfbe732e2020-01-24 11:26:14 -0800764 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
765 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700766 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700767 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
768 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800770 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000771 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000772 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 << "Should reject motion events with more than MAX_POINTERS pointers.";
774
775 // Rejects motion events with invalid pointer ids.
776 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800777 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
778 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700779 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700780 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
781 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700782 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800783 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000784 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000785 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 << "Should reject motion events with pointer ids less than 0.";
787
788 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800789 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
790 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700791 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700792 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
793 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700794 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800795 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000796 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000797 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
799
800 // Rejects motion events with duplicate pointer ids.
801 pointerProperties[0].id = 1;
802 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800803 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
804 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700805 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700806 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
807 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700808 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800809 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000810 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000811 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 << "Should reject motion events with duplicate pointer ids.";
813}
814
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800815/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
816
817TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
818 constexpr nsecs_t eventTime = 20;
Harry Cutts33476232023-01-30 19:57:29 +0000819 NotifyConfigurationChangedArgs args(/*id=*/10, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800820 mDispatcher->notifyConfigurationChanged(&args);
821 ASSERT_TRUE(mDispatcher->waitForIdle());
822
823 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
824}
825
826TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Harry Cutts33476232023-01-30 19:57:29 +0000827 NotifySwitchArgs args(/*id=*/10, /*eventTime=*/20, /*policyFlags=*/0, /*switchValues=*/1,
828 /*switchMask=*/2);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800829 mDispatcher->notifySwitch(&args);
830
831 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
832 args.policyFlags |= POLICY_FLAG_TRUSTED;
833 mFakePolicy->assertNotifySwitchWasCalled(args);
834}
835
Arthur Hungb92218b2018-08-14 12:00:21 +0800836// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700837static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700838// Default input dispatching timeout if there is no focused application or paused window
839// from which to determine an appropriate dispatching timeout.
840static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
841 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
842 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800843
844class FakeApplicationHandle : public InputApplicationHandle {
845public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700846 FakeApplicationHandle() {
847 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700848 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500849 mInfo.dispatchingTimeoutMillis =
850 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700851 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800852 virtual ~FakeApplicationHandle() {}
853
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000854 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700855
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500856 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
857 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700858 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800859};
860
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800861class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800862public:
Garfield Tan15601662020-09-22 15:32:38 -0700863 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800864 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700865 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800866 }
867
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800868 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700869 InputEvent* event;
870 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
871 if (!consumeSeq) {
872 return nullptr;
873 }
874 finishEvent(*consumeSeq);
875 return event;
876 }
877
878 /**
879 * Receive an event without acknowledging it.
880 * Return the sequence number that could later be used to send finished signal.
881 */
882 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800883 uint32_t consumeSeq;
884 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800885
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800886 std::chrono::time_point start = std::chrono::steady_clock::now();
887 status_t status = WOULD_BLOCK;
888 while (status == WOULD_BLOCK) {
Harry Cutts33476232023-01-30 19:57:29 +0000889 status = mConsumer->consume(&mEventFactory, /*consumeBatches=*/true, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800890 &event);
891 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
892 if (elapsed > 100ms) {
893 break;
894 }
895 }
896
897 if (status == WOULD_BLOCK) {
898 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700899 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800900 }
901
902 if (status != OK) {
903 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700904 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800905 }
906 if (event == nullptr) {
907 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700908 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800909 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700910 if (outEvent != nullptr) {
911 *outEvent = event;
912 }
913 return consumeSeq;
914 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800915
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700916 /**
917 * To be used together with "receiveEvent" to complete the consumption of an event.
918 */
919 void finishEvent(uint32_t consumeSeq) {
920 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
921 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800922 }
923
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000924 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
925 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
926 ASSERT_EQ(OK, status);
927 }
928
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000929 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
930 std::optional<int32_t> expectedDisplayId,
931 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800932 InputEvent* event = consume();
933
934 ASSERT_NE(nullptr, event) << mName.c_str()
935 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800936 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800938 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800939
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000940 if (expectedDisplayId.has_value()) {
941 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
942 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800943
Tiger Huang8664f8c2018-10-11 19:14:35 +0800944 switch (expectedEventType) {
945 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800946 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
947 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000948 if (expectedFlags.has_value()) {
949 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
950 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800951 break;
952 }
953 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800954 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000955 assertMotionAction(expectedAction, motionEvent.getAction());
956
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000957 if (expectedFlags.has_value()) {
958 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
959 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800960 break;
961 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100962 case AINPUT_EVENT_TYPE_FOCUS: {
963 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
964 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800965 case AINPUT_EVENT_TYPE_CAPTURE: {
966 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
967 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000968 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
969 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
970 }
arthurhungb89ccb02020-12-30 16:19:01 +0800971 case AINPUT_EVENT_TYPE_DRAG: {
972 FAIL() << "Use 'consumeDragEvent' for DRAG events";
973 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800974 default: {
975 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
976 }
977 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800978 }
979
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800980 MotionEvent* consumeMotion() {
981 InputEvent* event = consume();
982
983 if (event == nullptr) {
984 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
985 return nullptr;
986 }
987
988 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
989 ADD_FAILURE() << mName << " expected a MotionEvent, got "
990 << inputEventTypeToString(event->getType()) << " event";
991 return nullptr;
992 }
993 return static_cast<MotionEvent*>(event);
994 }
995
996 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
997 MotionEvent* motionEvent = consumeMotion();
998 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
999 ASSERT_THAT(*motionEvent, matcher);
1000 }
1001
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001002 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
1003 InputEvent* event = consume();
1004 ASSERT_NE(nullptr, event) << mName.c_str()
1005 << ": consumer should have returned non-NULL event.";
1006 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
1007 << "Got " << inputEventTypeToString(event->getType())
1008 << " event instead of FOCUS event";
1009
1010 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1011 << mName.c_str() << ": event displayId should always be NONE.";
1012
1013 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
1014 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001015 }
1016
Prabir Pradhan99987712020-11-10 18:43:05 -08001017 void consumeCaptureEvent(bool hasCapture) {
1018 const InputEvent* event = consume();
1019 ASSERT_NE(nullptr, event) << mName.c_str()
1020 << ": consumer should have returned non-NULL event.";
1021 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
1022 << "Got " << inputEventTypeToString(event->getType())
1023 << " event instead of CAPTURE event";
1024
1025 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1026 << mName.c_str() << ": event displayId should always be NONE.";
1027
1028 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1029 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1030 }
1031
arthurhungb89ccb02020-12-30 16:19:01 +08001032 void consumeDragEvent(bool isExiting, float x, float y) {
1033 const InputEvent* event = consume();
1034 ASSERT_NE(nullptr, event) << mName.c_str()
1035 << ": consumer should have returned non-NULL event.";
1036 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1037 << "Got " << inputEventTypeToString(event->getType())
1038 << " event instead of DRAG event";
1039
1040 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1041 << mName.c_str() << ": event displayId should always be NONE.";
1042
1043 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1044 EXPECT_EQ(isExiting, dragEvent.isExiting());
1045 EXPECT_EQ(x, dragEvent.getX());
1046 EXPECT_EQ(y, dragEvent.getY());
1047 }
1048
Antonio Kantekf16f2832021-09-28 04:39:20 +00001049 void consumeTouchModeEvent(bool inTouchMode) {
1050 const InputEvent* event = consume();
1051 ASSERT_NE(nullptr, event) << mName.c_str()
1052 << ": consumer should have returned non-NULL event.";
1053 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1054 << "Got " << inputEventTypeToString(event->getType())
1055 << " event instead of TOUCH_MODE event";
1056
1057 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1058 << mName.c_str() << ": event displayId should always be NONE.";
1059 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1060 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1061 }
1062
chaviwd1c23182019-12-20 18:44:56 -08001063 void assertNoEvents() {
1064 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001065 if (event == nullptr) {
1066 return;
1067 }
1068 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1069 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1070 ADD_FAILURE() << "Received key event "
1071 << KeyEvent::actionToString(keyEvent.getAction());
1072 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1073 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1074 ADD_FAILURE() << "Received motion event "
1075 << MotionEvent::actionToString(motionEvent.getAction());
1076 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1077 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1078 ADD_FAILURE() << "Received focus event, hasFocus = "
1079 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001080 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1081 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1082 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1083 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001084 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1085 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1086 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1087 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001088 }
1089 FAIL() << mName.c_str()
1090 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001091 }
1092
1093 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1094
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001095 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1096
chaviwd1c23182019-12-20 18:44:56 -08001097protected:
1098 std::unique_ptr<InputConsumer> mConsumer;
1099 PreallocatedInputEventFactory mEventFactory;
1100
1101 std::string mName;
1102};
1103
chaviw3277faf2021-05-19 16:45:23 -05001104class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001105public:
1106 static const int32_t WIDTH = 600;
1107 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001108
Chris Yea209fde2020-07-22 13:54:51 -07001109 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001110 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001111 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001112 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001113 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001114 base::Result<std::unique_ptr<InputChannel>> channel =
1115 dispatcher->createInputChannel(name);
1116 token = (*channel)->getConnectionToken();
1117 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001118 }
1119
1120 inputApplicationHandle->updateInfo();
1121 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1122
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001123 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001124 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001125 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001126 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001127 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001128 mInfo.frameLeft = 0;
1129 mInfo.frameTop = 0;
1130 mInfo.frameRight = WIDTH;
1131 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001132 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001133 mInfo.globalScaleFactor = 1.0;
1134 mInfo.touchableRegion.clear();
1135 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001136 mInfo.ownerPid = WINDOW_PID;
1137 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001138 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001139 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001140 }
1141
Arthur Hungabbb9d82021-09-01 14:52:30 +00001142 sp<FakeWindowHandle> clone(
1143 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001144 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001145 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001146 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1147 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001148 return handle;
1149 }
1150
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001151 void setTouchable(bool touchable) {
1152 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1153 }
chaviwd1c23182019-12-20 18:44:56 -08001154
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001155 void setFocusable(bool focusable) {
1156 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1157 }
1158
1159 void setVisible(bool visible) {
1160 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1161 }
Vishnu Nair958da932020-08-21 17:12:37 -07001162
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001163 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001164 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001165 }
1166
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001167 void setPaused(bool paused) {
1168 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1169 }
1170
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001171 void setPreventSplitting(bool preventSplitting) {
1172 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001173 }
1174
1175 void setSlippery(bool slippery) {
1176 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1177 }
1178
1179 void setWatchOutsideTouch(bool watchOutside) {
1180 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1181 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001182
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001183 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1184
1185 void setInterceptsStylus(bool interceptsStylus) {
1186 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1187 }
1188
1189 void setDropInput(bool dropInput) {
1190 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1191 }
1192
1193 void setDropInputIfObscured(bool dropInputIfObscured) {
1194 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1195 }
1196
1197 void setNoInputChannel(bool noInputChannel) {
1198 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1199 }
1200
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001201 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1202
chaviw3277faf2021-05-19 16:45:23 -05001203 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001204
Bernardo Rufino7393d172021-02-26 13:56:11 +00001205 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1206
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001207 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001208 mInfo.frameLeft = frame.left;
1209 mInfo.frameTop = frame.top;
1210 mInfo.frameRight = frame.right;
1211 mInfo.frameBottom = frame.bottom;
1212 mInfo.touchableRegion.clear();
1213 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001214
1215 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1216 ui::Transform translate;
1217 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1218 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001219 }
1220
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001221 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1222
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001223 void setIsWallpaper(bool isWallpaper) {
1224 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1225 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001226
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001227 void setDupTouchToWallpaper(bool hasWallpaper) {
1228 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1229 }
chaviwd1c23182019-12-20 18:44:56 -08001230
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001231 void setTrustedOverlay(bool trustedOverlay) {
1232 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1233 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001234
chaviw9eaa22c2020-07-01 16:21:27 -07001235 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1236 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1237 }
1238
1239 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001240
yunho.shinf4a80b82020-11-16 21:13:57 +09001241 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1242
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001243 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1244 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1245 expectedFlags);
1246 }
1247
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001248 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1249 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1250 }
1251
Svet Ganov5d3bc372020-01-26 23:11:07 -08001252 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001253 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001254 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1255 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001256 }
1257
1258 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001259 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001260 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1261 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001262 }
1263
1264 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001265 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001266 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1267 }
1268
1269 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1270 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001271 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1272 expectedFlags);
1273 }
1274
Svet Ganov5d3bc372020-01-26 23:11:07 -08001275 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001276 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1277 int32_t expectedFlags = 0) {
1278 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1279 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001280 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1281 }
1282
1283 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001284 int32_t expectedFlags = 0) {
1285 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1286 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001287 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1288 }
1289
1290 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001291 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001292 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1293 expectedFlags);
1294 }
1295
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001296 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1297 int32_t expectedFlags = 0) {
1298 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1299 expectedFlags);
1300 }
1301
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001302 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1303 int32_t expectedFlags = 0) {
1304 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001305 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001306 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1307 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1308 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1309 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1310 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1311 }
1312
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001313 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1314 ASSERT_NE(mInputReceiver, nullptr)
1315 << "Cannot consume events from a window with no receiver";
1316 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1317 }
1318
Prabir Pradhan99987712020-11-10 18:43:05 -08001319 void consumeCaptureEvent(bool hasCapture) {
1320 ASSERT_NE(mInputReceiver, nullptr)
1321 << "Cannot consume events from a window with no receiver";
1322 mInputReceiver->consumeCaptureEvent(hasCapture);
1323 }
1324
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001325 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1326 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001327 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001328 ASSERT_THAT(*motionEvent, matcher);
1329 }
1330
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001331 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1332 std::optional<int32_t> expectedDisplayId,
1333 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001334 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1335 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1336 expectedFlags);
1337 }
1338
arthurhungb89ccb02020-12-30 16:19:01 +08001339 void consumeDragEvent(bool isExiting, float x, float y) {
1340 mInputReceiver->consumeDragEvent(isExiting, x, y);
1341 }
1342
Antonio Kantekf16f2832021-09-28 04:39:20 +00001343 void consumeTouchModeEvent(bool inTouchMode) {
1344 ASSERT_NE(mInputReceiver, nullptr)
1345 << "Cannot consume events from a window with no receiver";
1346 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1347 }
1348
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001349 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001350 if (mInputReceiver == nullptr) {
1351 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1352 return std::nullopt;
1353 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001354 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001355 }
1356
1357 void finishEvent(uint32_t sequenceNum) {
1358 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1359 mInputReceiver->finishEvent(sequenceNum);
1360 }
1361
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001362 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1363 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1364 mInputReceiver->sendTimeline(inputEventId, timeline);
1365 }
1366
chaviwaf87b3e2019-10-01 16:59:28 -07001367 InputEvent* consume() {
1368 if (mInputReceiver == nullptr) {
1369 return nullptr;
1370 }
1371 return mInputReceiver->consume();
1372 }
1373
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001374 MotionEvent* consumeMotion() {
1375 InputEvent* event = consume();
1376 if (event == nullptr) {
1377 ADD_FAILURE() << "Consume failed : no event";
1378 return nullptr;
1379 }
1380 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1381 ADD_FAILURE() << "Instead of motion event, got "
1382 << inputEventTypeToString(event->getType());
1383 return nullptr;
1384 }
1385 return static_cast<MotionEvent*>(event);
1386 }
1387
Arthur Hungb92218b2018-08-14 12:00:21 +08001388 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001389 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001390 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001391 return; // Can't receive events if the window does not have input channel
1392 }
1393 ASSERT_NE(nullptr, mInputReceiver)
1394 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001395 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001396 }
1397
chaviwaf87b3e2019-10-01 16:59:28 -07001398 sp<IBinder> getToken() { return mInfo.token; }
1399
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001400 const std::string& getName() { return mName; }
1401
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001402 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1403 mInfo.ownerPid = ownerPid;
1404 mInfo.ownerUid = ownerUid;
1405 }
1406
Prabir Pradhanedd96402022-02-15 01:46:16 -08001407 int32_t getPid() const { return mInfo.ownerPid; }
1408
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001409 void destroyReceiver() { mInputReceiver = nullptr; }
1410
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001411 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1412
chaviwd1c23182019-12-20 18:44:56 -08001413private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001414 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001415 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001416 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001417};
1418
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001419std::atomic<int32_t> FakeWindowHandle::sId{1};
1420
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001422 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001423 int32_t displayId = ADISPLAY_ID_NONE,
1424 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001425 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001426 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1427 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001428 KeyEvent event;
1429 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1430
1431 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001432 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Harry Cutts33476232023-01-30 19:57:29 +00001433 INVALID_HMAC, action, /*flags=*/0, AKEYCODE_A, KEY_A, AMETA_NONE, repeatCount,
1434 currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001435
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001436 if (!allowKeyRepeat) {
1437 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1438 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001439 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001440 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001441}
1442
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001443static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001444 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001445 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001446}
1447
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001448// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1449// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1450// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001451static InputEventInjectionResult injectKeyDownNoRepeat(
1452 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001453 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001454 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
Harry Cutts33476232023-01-30 19:57:29 +00001455 /*allowKeyRepeat=*/false);
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001456}
1457
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001458static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001460 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /*repeatCount=*/0, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001461}
1462
Garfield Tandf26e862020-07-01 20:18:19 -07001463class PointerBuilder {
1464public:
1465 PointerBuilder(int32_t id, int32_t toolType) {
1466 mProperties.clear();
1467 mProperties.id = id;
1468 mProperties.toolType = toolType;
1469 mCoords.clear();
1470 }
1471
1472 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1473
1474 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1475
1476 PointerBuilder& axis(int32_t axis, float value) {
1477 mCoords.setAxisValue(axis, value);
1478 return *this;
1479 }
1480
1481 PointerProperties buildProperties() const { return mProperties; }
1482
1483 PointerCoords buildCoords() const { return mCoords; }
1484
1485private:
1486 PointerProperties mProperties;
1487 PointerCoords mCoords;
1488};
1489
1490class MotionEventBuilder {
1491public:
1492 MotionEventBuilder(int32_t action, int32_t source) {
1493 mAction = action;
1494 mSource = source;
1495 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001496 mDownTime = mEventTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001497 }
1498
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001499 MotionEventBuilder& deviceId(int32_t deviceId) {
1500 mDeviceId = deviceId;
1501 return *this;
1502 }
1503
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001504 MotionEventBuilder& downTime(nsecs_t downTime) {
1505 mDownTime = downTime;
1506 return *this;
1507 }
1508
Garfield Tandf26e862020-07-01 20:18:19 -07001509 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1510 mEventTime = eventTime;
1511 return *this;
1512 }
1513
1514 MotionEventBuilder& displayId(int32_t displayId) {
1515 mDisplayId = displayId;
1516 return *this;
1517 }
1518
1519 MotionEventBuilder& actionButton(int32_t actionButton) {
1520 mActionButton = actionButton;
1521 return *this;
1522 }
1523
arthurhung6d4bed92021-03-17 11:59:33 +08001524 MotionEventBuilder& buttonState(int32_t buttonState) {
1525 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001526 return *this;
1527 }
1528
1529 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1530 mRawXCursorPosition = rawXCursorPosition;
1531 return *this;
1532 }
1533
1534 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1535 mRawYCursorPosition = rawYCursorPosition;
1536 return *this;
1537 }
1538
1539 MotionEventBuilder& pointer(PointerBuilder pointer) {
1540 mPointers.push_back(pointer);
1541 return *this;
1542 }
1543
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001544 MotionEventBuilder& addFlag(uint32_t flags) {
1545 mFlags |= flags;
1546 return *this;
1547 }
1548
Garfield Tandf26e862020-07-01 20:18:19 -07001549 MotionEvent build() {
1550 std::vector<PointerProperties> pointerProperties;
1551 std::vector<PointerCoords> pointerCoords;
1552 for (const PointerBuilder& pointer : mPointers) {
1553 pointerProperties.push_back(pointer.buildProperties());
1554 pointerCoords.push_back(pointer.buildCoords());
1555 }
1556
1557 // Set mouse cursor position for the most common cases to avoid boilerplate.
1558 if (mSource == AINPUT_SOURCE_MOUSE &&
1559 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1560 mPointers.size() == 1) {
1561 mRawXCursorPosition = pointerCoords[0].getX();
1562 mRawYCursorPosition = pointerCoords[0].getY();
1563 }
1564
1565 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001566 ui::Transform identityTransform;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001567 event.initialize(InputEvent::nextId(), mDeviceId, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001568 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001569 mButtonState, MotionClassification::NONE, identityTransform,
1570 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001571 mRawYCursorPosition, identityTransform, mDownTime, mEventTime,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001572 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001573
1574 return event;
1575 }
1576
1577private:
1578 int32_t mAction;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001579 int32_t mDeviceId = DEVICE_ID;
Garfield Tandf26e862020-07-01 20:18:19 -07001580 int32_t mSource;
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001581 nsecs_t mDownTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001582 nsecs_t mEventTime;
1583 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1584 int32_t mActionButton{0};
1585 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001586 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001587 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1588 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1589
1590 std::vector<PointerBuilder> mPointers;
1591};
1592
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08001593class MotionArgsBuilder {
1594public:
1595 MotionArgsBuilder(int32_t action, int32_t source) {
1596 mAction = action;
1597 mSource = source;
1598 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1599 mDownTime = mEventTime;
1600 }
1601
1602 MotionArgsBuilder& deviceId(int32_t deviceId) {
1603 mDeviceId = deviceId;
1604 return *this;
1605 }
1606
1607 MotionArgsBuilder& downTime(nsecs_t downTime) {
1608 mDownTime = downTime;
1609 return *this;
1610 }
1611
1612 MotionArgsBuilder& eventTime(nsecs_t eventTime) {
1613 mEventTime = eventTime;
1614 return *this;
1615 }
1616
1617 MotionArgsBuilder& displayId(int32_t displayId) {
1618 mDisplayId = displayId;
1619 return *this;
1620 }
1621
1622 MotionArgsBuilder& policyFlags(int32_t policyFlags) {
1623 mPolicyFlags = policyFlags;
1624 return *this;
1625 }
1626
1627 MotionArgsBuilder& actionButton(int32_t actionButton) {
1628 mActionButton = actionButton;
1629 return *this;
1630 }
1631
1632 MotionArgsBuilder& buttonState(int32_t buttonState) {
1633 mButtonState = buttonState;
1634 return *this;
1635 }
1636
1637 MotionArgsBuilder& rawXCursorPosition(float rawXCursorPosition) {
1638 mRawXCursorPosition = rawXCursorPosition;
1639 return *this;
1640 }
1641
1642 MotionArgsBuilder& rawYCursorPosition(float rawYCursorPosition) {
1643 mRawYCursorPosition = rawYCursorPosition;
1644 return *this;
1645 }
1646
1647 MotionArgsBuilder& pointer(PointerBuilder pointer) {
1648 mPointers.push_back(pointer);
1649 return *this;
1650 }
1651
1652 MotionArgsBuilder& addFlag(uint32_t flags) {
1653 mFlags |= flags;
1654 return *this;
1655 }
1656
1657 NotifyMotionArgs build() {
1658 std::vector<PointerProperties> pointerProperties;
1659 std::vector<PointerCoords> pointerCoords;
1660 for (const PointerBuilder& pointer : mPointers) {
1661 pointerProperties.push_back(pointer.buildProperties());
1662 pointerCoords.push_back(pointer.buildCoords());
1663 }
1664
1665 // Set mouse cursor position for the most common cases to avoid boilerplate.
1666 if (mSource == AINPUT_SOURCE_MOUSE &&
1667 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1668 mPointers.size() == 1) {
1669 mRawXCursorPosition = pointerCoords[0].getX();
1670 mRawYCursorPosition = pointerCoords[0].getY();
1671 }
1672
1673 NotifyMotionArgs args(InputEvent::nextId(), mEventTime, /*readTime=*/mEventTime, mDeviceId,
1674 mSource, mDisplayId, mPolicyFlags, mAction, mActionButton, mFlags,
1675 AMETA_NONE, mButtonState, MotionClassification::NONE, /*edgeFlags=*/0,
1676 mPointers.size(), pointerProperties.data(), pointerCoords.data(),
1677 /*xPrecision=*/0, /*yPrecision=*/0, mRawXCursorPosition,
1678 mRawYCursorPosition, mDownTime, /*videoFrames=*/{});
1679
1680 return args;
1681 }
1682
1683private:
1684 int32_t mAction;
1685 int32_t mDeviceId = DEVICE_ID;
1686 int32_t mSource;
1687 nsecs_t mDownTime;
1688 nsecs_t mEventTime;
1689 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1690 int32_t mPolicyFlags = DEFAULT_POLICY_FLAGS;
1691 int32_t mActionButton{0};
1692 int32_t mButtonState{0};
1693 int32_t mFlags{0};
1694 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1695 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1696
1697 std::vector<PointerBuilder> mPointers;
1698};
1699
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001700static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001701 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001702 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001703 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1704 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1705 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1706 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001707}
1708
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001709static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001710 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001711 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001712 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1714 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001716 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1717 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001718 MotionEvent event = MotionEventBuilder(action, source)
1719 .displayId(displayId)
1720 .eventTime(eventTime)
1721 .rawXCursorPosition(cursorPosition.x)
1722 .rawYCursorPosition(cursorPosition.y)
Harry Cutts33476232023-01-30 19:57:29 +00001723 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001724 .x(position.x)
1725 .y(position.y))
1726 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001727
1728 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001729 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1730 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001731}
1732
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001733static InputEventInjectionResult injectMotionDown(
1734 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1735 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001736 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001737}
1738
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001739static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 int32_t source, int32_t displayId,
1741 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001742 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001743}
1744
Jackal Guof9696682018-10-05 12:23:23 +08001745static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1746 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1747 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001748 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001749 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1750 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001751
1752 return args;
1753}
1754
chaviwd1c23182019-12-20 18:44:56 -08001755static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1756 const std::vector<PointF>& points) {
1757 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001758 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1759 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1760 }
1761
chaviwd1c23182019-12-20 18:44:56 -08001762 PointerProperties pointerProperties[pointerCount];
1763 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001764
chaviwd1c23182019-12-20 18:44:56 -08001765 for (size_t i = 0; i < pointerCount; i++) {
1766 pointerProperties[i].clear();
1767 pointerProperties[i].id = i;
1768 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001769
chaviwd1c23182019-12-20 18:44:56 -08001770 pointerCoords[i].clear();
1771 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1772 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1773 }
Jackal Guof9696682018-10-05 12:23:23 +08001774
1775 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1776 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001777 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001778 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1779 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001780 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1781 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001782 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1783 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001784
1785 return args;
1786}
1787
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001788static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1789 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1790}
1791
chaviwd1c23182019-12-20 18:44:56 -08001792static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1793 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1794}
1795
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001796static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1797 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001798 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001799}
1800
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001801/**
1802 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1803 * broken channel.
1804 */
1805TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1806 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1807 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001808 sp<FakeWindowHandle>::make(application, mDispatcher,
1809 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001810
1811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1812
1813 // Window closes its channel, but the window remains.
1814 window->destroyReceiver();
1815 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1816}
1817
Arthur Hungb92218b2018-08-14 12:00:21 +08001818TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001819 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001820 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1821 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001822
Arthur Hung72d8dc32020-03-28 00:48:39 +00001823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1825 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001827
1828 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001829 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001830}
1831
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001832TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1833 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001834 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1835 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001836
1837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1838 // Inject a MotionEvent to an unknown display.
1839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1840 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1842
1843 // Window should receive motion event.
1844 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1845}
1846
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001847/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001848 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001849 * This test serves as a sanity check for the next test, where setInputWindows is
1850 * called twice.
1851 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001852TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001853 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001854 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1855 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001856 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001857
1858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001860 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1861 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001863
1864 // Window should receive motion event.
1865 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1866}
1867
1868/**
1869 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001870 */
1871TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001873 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1874 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001875 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001876
1877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001880 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1881 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001883
1884 // Window should receive motion event.
1885 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1886}
1887
Arthur Hungb92218b2018-08-14 12:00:21 +08001888// The foreground window should receive the first touch down event.
1889TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001890 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001891 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001892 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001893 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001894 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001895
Arthur Hung72d8dc32020-03-28 00:48:39 +00001896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1898 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1899 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001900
1901 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001902 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001903 windowSecond->assertNoEvents();
1904}
1905
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001906/**
1907 * Two windows: A top window, and a wallpaper behind the window.
1908 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1909 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001910 * 1. foregroundWindow <-- dup touch to wallpaper
1911 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001912 */
1913TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1914 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1915 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001916 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001917 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001918 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001919 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001920 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001921
1922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1923 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1924 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1925 {100, 200}))
1926 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1927
1928 // Both foreground window and its wallpaper should receive the touch down
1929 foregroundWindow->consumeMotionDown();
1930 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1931
1932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1933 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1934 ADISPLAY_ID_DEFAULT, {110, 200}))
1935 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1936
1937 foregroundWindow->consumeMotionMove();
1938 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1939
1940 // Now the foreground window goes away, but the wallpaper stays
1941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1942 foregroundWindow->consumeMotionCancel();
1943 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1944 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1945}
1946
1947/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001948 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1949 * with the following differences:
1950 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1951 * clean up the connection.
1952 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1953 * Ensure that there's no crash in the dispatcher.
1954 */
1955TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1957 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001958 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001959 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001960 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001961 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001962 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001963
1964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1966 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1967 {100, 200}))
1968 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1969
1970 // Both foreground window and its wallpaper should receive the touch down
1971 foregroundWindow->consumeMotionDown();
1972 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1973
1974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1976 ADISPLAY_ID_DEFAULT, {110, 200}))
1977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1978
1979 foregroundWindow->consumeMotionMove();
1980 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1981
1982 // Wallpaper closes its channel, but the window remains.
1983 wallpaperWindow->destroyReceiver();
1984 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1985
1986 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1987 // is no longer valid.
1988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1989 foregroundWindow->consumeMotionCancel();
1990}
1991
Arthur Hungc539dbb2022-12-08 07:45:36 +00001992class ShouldSplitTouchFixture : public InputDispatcherTest,
1993 public ::testing::WithParamInterface<bool> {};
1994INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1995 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001996/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001997 * A single window that receives touch (on top), and a wallpaper window underneath it.
1998 * The top window gets a multitouch gesture.
1999 * Ensure that wallpaper gets the same gesture.
2000 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00002001TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002002 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002003 sp<FakeWindowHandle> foregroundWindow =
2004 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2005 foregroundWindow->setDupTouchToWallpaper(true);
2006 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002007
2008 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002009 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002010 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002011
Arthur Hungc539dbb2022-12-08 07:45:36 +00002012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002013
2014 // Touch down on top window
2015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2017 {100, 100}))
2018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2019
2020 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00002021 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002022 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2023
2024 // Second finger down on the top window
2025 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002026 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002027 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002028 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2029 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002030 .build();
2031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2032 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2033 InputEventInjectionSync::WAIT_FOR_RESULT))
2034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2035
Harry Cutts33476232023-01-30 19:57:29 +00002036 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
2037 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002038 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002039
2040 const MotionEvent secondFingerUpEvent =
2041 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2042 .displayId(ADISPLAY_ID_DEFAULT)
2043 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002044 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2045 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002046 .build();
2047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2048 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
2049 InputEventInjectionSync::WAIT_FOR_RESULT))
2050 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2051 foregroundWindow->consumeMotionPointerUp(0);
2052 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2053
2054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08002055 injectMotionEvent(mDispatcher,
2056 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2057 AINPUT_SOURCE_TOUCHSCREEN)
2058 .displayId(ADISPLAY_ID_DEFAULT)
2059 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2060 .pointer(PointerBuilder(/* id */ 1,
2061 AMOTION_EVENT_TOOL_TYPE_FINGER)
2062 .x(100)
2063 .y(100))
2064 .build(),
2065 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002066 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2067 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2068 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002069}
2070
2071/**
2072 * Two windows: a window on the left and window on the right.
2073 * A third window, wallpaper, is behind both windows, and spans both top windows.
2074 * The first touch down goes to the left window. A second pointer touches down on the right window.
2075 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2076 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2077 * ACTION_POINTER_DOWN(1).
2078 */
2079TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2080 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2081 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002082 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002083 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002084 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002085
2086 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002087 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002088 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002089 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002090
2091 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002092 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002093 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002094 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002095
2096 mDispatcher->setInputWindows(
2097 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2098
2099 // Touch down on left window
2100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2101 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2102 {100, 100}))
2103 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2104
2105 // Both foreground window and its wallpaper should receive the touch down
2106 leftWindow->consumeMotionDown();
2107 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2108
2109 // Second finger down on the right window
2110 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002111 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002112 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002113 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2114 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002115 .build();
2116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2117 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2118 InputEventInjectionSync::WAIT_FOR_RESULT))
2119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2120
2121 leftWindow->consumeMotionMove();
2122 // Since the touch is split, right window gets ACTION_DOWN
2123 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002124 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002125 expectedWallpaperFlags);
2126
2127 // Now, leftWindow, which received the first finger, disappears.
2128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2129 leftWindow->consumeMotionCancel();
2130 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2131 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2132
2133 // The pointer that's still down on the right window moves, and goes to the right window only.
2134 // As far as the dispatcher's concerned though, both pointers are still present.
2135 const MotionEvent secondFingerMoveEvent =
2136 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2137 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002138 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2139 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002140 .build();
2141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2142 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2143 InputEventInjectionSync::WAIT_FOR_RESULT));
2144 rightWindow->consumeMotionMove();
2145
2146 leftWindow->assertNoEvents();
2147 rightWindow->assertNoEvents();
2148 wallpaperWindow->assertNoEvents();
2149}
2150
Arthur Hungc539dbb2022-12-08 07:45:36 +00002151/**
2152 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2153 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2154 * The right window should receive ACTION_DOWN.
2155 */
2156TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002158 sp<FakeWindowHandle> leftWindow =
2159 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2160 leftWindow->setFrame(Rect(0, 0, 200, 200));
2161 leftWindow->setDupTouchToWallpaper(true);
2162 leftWindow->setSlippery(true);
2163
2164 sp<FakeWindowHandle> rightWindow =
2165 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2166 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002167
2168 sp<FakeWindowHandle> wallpaperWindow =
2169 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2170 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002171
Arthur Hungc539dbb2022-12-08 07:45:36 +00002172 mDispatcher->setInputWindows(
2173 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002174
Arthur Hungc539dbb2022-12-08 07:45:36 +00002175 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2177 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002178 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002179 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002180
2181 // Both foreground window and its wallpaper should receive the touch down
2182 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002183 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2184
Arthur Hungc539dbb2022-12-08 07:45:36 +00002185 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002187 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2188 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002189 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2190
Arthur Hungc539dbb2022-12-08 07:45:36 +00002191 leftWindow->consumeMotionCancel();
2192 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2193 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002194}
2195
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002196/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002197 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2198 * interactive, it might stop sending this flag.
2199 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2200 * to have a consistent input stream.
2201 *
2202 * Test procedure:
2203 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2204 * DOWN (new gesture).
2205 *
2206 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2207 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2208 *
2209 * We technically just need a single window here, but we are using two windows (spy on top and a
2210 * regular window below) to emulate the actual situation where it happens on the device.
2211 */
2212TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2213 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2214 sp<FakeWindowHandle> spyWindow =
2215 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2216 spyWindow->setFrame(Rect(0, 0, 200, 200));
2217 spyWindow->setTrustedOverlay(true);
2218 spyWindow->setSpy(true);
2219
2220 sp<FakeWindowHandle> window =
2221 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2222 window->setFrame(Rect(0, 0, 200, 200));
2223
2224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2225 const int32_t touchDeviceId = 4;
2226 NotifyMotionArgs args;
2227
2228 // Two pointers down
2229 mDispatcher->notifyMotion(&(
2230 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2231 .deviceId(touchDeviceId)
2232 .policyFlags(DEFAULT_POLICY_FLAGS)
2233 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2234 .build()));
2235
2236 mDispatcher->notifyMotion(&(
2237 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2238 .deviceId(touchDeviceId)
2239 .policyFlags(DEFAULT_POLICY_FLAGS)
2240 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2241 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2242 .build()));
2243 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2244 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2245 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2246 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2247
2248 // Cancel the current gesture. Send the cancel without the default policy flags.
2249 mDispatcher->notifyMotion(&(
2250 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2251 .deviceId(touchDeviceId)
2252 .policyFlags(0)
2253 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2254 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2255 .build()));
2256 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2257 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2258
2259 // We don't need to reset the device to reproduce the issue, but the reset event typically
2260 // follows, so we keep it here to model the actual listener behaviour more closely.
2261 NotifyDeviceResetArgs resetArgs;
2262 resetArgs.id = 1; // arbitrary id
2263 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2264 resetArgs.deviceId = touchDeviceId;
2265 mDispatcher->notifyDeviceReset(&resetArgs);
2266
2267 // Start new gesture
2268 mDispatcher->notifyMotion(&(
2269 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2270 .deviceId(touchDeviceId)
2271 .policyFlags(DEFAULT_POLICY_FLAGS)
2272 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2273 .build()));
2274 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2275 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2276
2277 // No more events
2278 spyWindow->assertNoEvents();
2279 window->assertNoEvents();
2280}
2281
2282/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002283 * Two windows: a window on the left and a window on the right.
2284 * Mouse is hovered from the right window into the left window.
2285 * Next, we tap on the left window, where the cursor was last seen.
2286 * The second tap is done onto the right window.
2287 * The mouse and tap are from two different devices.
2288 * We technically don't need to set the downtime / eventtime for these events, but setting these
2289 * explicitly helps during debugging.
2290 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2291 * In the buggy implementation, a tap on the right window would cause a crash.
2292 */
2293TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2294 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2295 sp<FakeWindowHandle> leftWindow =
2296 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2297 leftWindow->setFrame(Rect(0, 0, 200, 200));
2298
2299 sp<FakeWindowHandle> rightWindow =
2300 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2301 rightWindow->setFrame(Rect(200, 0, 400, 200));
2302
2303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2304 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2305 // stale.
2306 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2307 const int32_t mouseDeviceId = 6;
2308 const int32_t touchDeviceId = 4;
2309 // Move the cursor from right
2310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2311 injectMotionEvent(mDispatcher,
2312 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2313 AINPUT_SOURCE_MOUSE)
2314 .deviceId(mouseDeviceId)
2315 .downTime(baseTime + 10)
2316 .eventTime(baseTime + 20)
2317 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2318 .x(300)
2319 .y(100))
2320 .build()));
2321 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2322
2323 // .. to the left window
2324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2325 injectMotionEvent(mDispatcher,
2326 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2327 AINPUT_SOURCE_MOUSE)
2328 .deviceId(mouseDeviceId)
2329 .downTime(baseTime + 10)
2330 .eventTime(baseTime + 30)
2331 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2332 .x(110)
2333 .y(100))
2334 .build()));
2335 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2336 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2337 // Now tap the left window
2338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2339 injectMotionEvent(mDispatcher,
2340 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2341 AINPUT_SOURCE_TOUCHSCREEN)
2342 .deviceId(touchDeviceId)
2343 .downTime(baseTime + 40)
2344 .eventTime(baseTime + 40)
2345 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2346 .x(100)
2347 .y(100))
2348 .build()));
2349 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2350 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2351
2352 // release tap
2353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2354 injectMotionEvent(mDispatcher,
2355 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2356 AINPUT_SOURCE_TOUCHSCREEN)
2357 .deviceId(touchDeviceId)
2358 .downTime(baseTime + 40)
2359 .eventTime(baseTime + 50)
2360 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2361 .x(100)
2362 .y(100))
2363 .build()));
2364 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2365
2366 // Tap the window on the right
2367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2368 injectMotionEvent(mDispatcher,
2369 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2370 AINPUT_SOURCE_TOUCHSCREEN)
2371 .deviceId(touchDeviceId)
2372 .downTime(baseTime + 60)
2373 .eventTime(baseTime + 60)
2374 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2375 .x(300)
2376 .y(100))
2377 .build()));
2378 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2379
2380 // release tap
2381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2382 injectMotionEvent(mDispatcher,
2383 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2384 AINPUT_SOURCE_TOUCHSCREEN)
2385 .deviceId(touchDeviceId)
2386 .downTime(baseTime + 60)
2387 .eventTime(baseTime + 70)
2388 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2389 .x(300)
2390 .y(100))
2391 .build()));
2392 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2393
2394 // No more events
2395 leftWindow->assertNoEvents();
2396 rightWindow->assertNoEvents();
2397}
2398
2399/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002400 * Two windows: a window on the left and a window on the right.
2401 * Mouse is clicked on the left window and remains down. Touch is touched on the right and remains
2402 * down. Then, on the left window, also place second touch pointer down.
2403 * This test tries to reproduce a crash.
2404 * In the buggy implementation, second pointer down on the left window would cause a crash.
2405 */
2406TEST_F(InputDispatcherTest, MultiDeviceSplitTouch) {
2407 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2408 sp<FakeWindowHandle> leftWindow =
2409 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2410 leftWindow->setFrame(Rect(0, 0, 200, 200));
2411
2412 sp<FakeWindowHandle> rightWindow =
2413 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2414 rightWindow->setFrame(Rect(200, 0, 400, 200));
2415
2416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2417
2418 const int32_t touchDeviceId = 4;
2419 const int32_t mouseDeviceId = 6;
2420 NotifyMotionArgs args;
2421
2422 // Start hovering over the left window
2423 mDispatcher->notifyMotion(&(
2424 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2425 .deviceId(mouseDeviceId)
2426 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2427 .build()));
2428 leftWindow->consumeMotionEvent(
2429 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2430
2431 // Mouse down on left window
2432 mDispatcher->notifyMotion(&(
2433 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2434 .deviceId(mouseDeviceId)
2435 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2436 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2437 .build()));
2438
2439 leftWindow->consumeMotionEvent(
2440 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
2441 leftWindow->consumeMotionEvent(
2442 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2443
2444 mDispatcher->notifyMotion(&(
2445 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2446 .deviceId(mouseDeviceId)
2447 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2448 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2449 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2450 .build()));
2451 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2452
2453 // First touch pointer down on right window
2454 mDispatcher->notifyMotion(&(
2455 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2456 .deviceId(touchDeviceId)
2457 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2458 .build()));
2459 leftWindow->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2460
2461 rightWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2462
2463 // Second touch pointer down on left window
2464 mDispatcher->notifyMotion(&(
2465 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2466 .deviceId(touchDeviceId)
2467 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2468 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2469 .build()));
2470 leftWindow->consumeMotionEvent(
2471 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2472 // This MOVE event is not necessary (doesn't carry any new information), but it's there in the
2473 // current implementation.
2474 const std::map<int32_t, PointF> expectedPointers{{0, PointF{100, 100}}};
2475 rightWindow->consumeMotionEvent(
2476 AllOf(WithMotionAction(ACTION_MOVE), WithPointers(expectedPointers)));
2477
2478 leftWindow->assertNoEvents();
2479 rightWindow->assertNoEvents();
2480}
2481
2482/**
2483 * On a single window, use two different devices: mouse and touch.
2484 * Touch happens first, with two pointers going down, and then the first pointer leaving.
2485 * Mouse is clicked next, which causes the touch stream to be aborted with ACTION_CANCEL.
2486 * Finally, a second touch pointer goes down again. Ensure the second touch pointer is ignored,
2487 * because the mouse is currently down, and a POINTER_DOWN event from the touchscreen does not
2488 * represent a new gesture.
2489 */
2490TEST_F(InputDispatcherTest, MixedTouchAndMouseWithPointerDown) {
2491 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2492 sp<FakeWindowHandle> window =
2493 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2494 window->setFrame(Rect(0, 0, 400, 400));
2495
2496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2497
2498 const int32_t touchDeviceId = 4;
2499 const int32_t mouseDeviceId = 6;
2500 NotifyMotionArgs args;
2501
2502 // First touch pointer down on right window
2503 mDispatcher->notifyMotion(&(
2504 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2505 .deviceId(touchDeviceId)
2506 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2507 .build()));
2508 // Second touch pointer down
2509 mDispatcher->notifyMotion(&(
2510 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2511 .deviceId(touchDeviceId)
2512 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2513 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2514 .build()));
2515 // First touch pointer lifts. The second one remains down
2516 mDispatcher->notifyMotion(&(
2517 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2518 .deviceId(touchDeviceId)
2519 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2520 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2521 .build()));
2522 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2523 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2524 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
2525
2526 // Mouse down. The touch should be canceled
2527 mDispatcher->notifyMotion(&(
2528 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2529 .deviceId(mouseDeviceId)
2530 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2531 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2532 .build()));
2533
2534 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
2535 WithPointerCount(2u)));
2536 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2537
2538 mDispatcher->notifyMotion(&(
2539 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2540 .deviceId(mouseDeviceId)
2541 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2542 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2543 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2544 .build()));
2545 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2546
2547 // Second touch pointer down.
2548 mDispatcher->notifyMotion(&(
2549 args = MotionArgsBuilder(POINTER_0_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2550 .deviceId(touchDeviceId)
2551 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2552 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2553 .build()));
2554 // The pointer_down event should be ignored
2555 window->assertNoEvents();
2556}
2557
2558/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002559 * This test is similar to the test above, but the sequence of injected events is different.
2560 *
2561 * Two windows: a window on the left and a window on the right.
2562 * Mouse is hovered over the left window.
2563 * Next, we tap on the left window, where the cursor was last seen.
2564 *
2565 * After that, we inject one finger down onto the right window, and then a second finger down onto
2566 * the left window.
2567 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2568 * window (first), and then another on the left window (second).
2569 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2570 * In the buggy implementation, second finger down on the left window would cause a crash.
2571 */
2572TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2573 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2574 sp<FakeWindowHandle> leftWindow =
2575 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2576 leftWindow->setFrame(Rect(0, 0, 200, 200));
2577
2578 sp<FakeWindowHandle> rightWindow =
2579 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2580 rightWindow->setFrame(Rect(200, 0, 400, 200));
2581
2582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2583
2584 const int32_t mouseDeviceId = 6;
2585 const int32_t touchDeviceId = 4;
2586 // Hover over the left window. Keep the cursor there.
2587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2588 injectMotionEvent(mDispatcher,
2589 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2590 AINPUT_SOURCE_MOUSE)
2591 .deviceId(mouseDeviceId)
2592 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2593 .x(50)
2594 .y(50))
2595 .build()));
2596 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2597
2598 // Tap on left window
2599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2600 injectMotionEvent(mDispatcher,
2601 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2602 AINPUT_SOURCE_TOUCHSCREEN)
2603 .deviceId(touchDeviceId)
2604 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2605 .x(100)
2606 .y(100))
2607 .build()));
2608
2609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2610 injectMotionEvent(mDispatcher,
2611 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2612 AINPUT_SOURCE_TOUCHSCREEN)
2613 .deviceId(touchDeviceId)
2614 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2615 .x(100)
2616 .y(100))
2617 .build()));
2618 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2619 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2620 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2621
2622 // First finger down on right window
2623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2624 injectMotionEvent(mDispatcher,
2625 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2626 AINPUT_SOURCE_TOUCHSCREEN)
2627 .deviceId(touchDeviceId)
2628 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2629 .x(300)
2630 .y(100))
2631 .build()));
2632 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2633
2634 // Second finger down on the left window
2635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2636 injectMotionEvent(mDispatcher,
2637 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2638 .deviceId(touchDeviceId)
2639 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2640 .x(300)
2641 .y(100))
2642 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2643 .x(100)
2644 .y(100))
2645 .build()));
2646 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2647 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2648
2649 // No more events
2650 leftWindow->assertNoEvents();
2651 rightWindow->assertNoEvents();
2652}
2653
2654/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002655 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2656 * While the touch is down, new hover events from the stylus device should be ignored. After the
2657 * touch is gone, stylus hovering should start working again.
2658 */
2659TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2661 sp<FakeWindowHandle> window =
2662 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2663 window->setFrame(Rect(0, 0, 200, 200));
2664
2665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2666
2667 const int32_t stylusDeviceId = 5;
2668 const int32_t touchDeviceId = 4;
2669 // Start hovering with stylus
2670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2671 injectMotionEvent(mDispatcher,
2672 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2673 AINPUT_SOURCE_STYLUS)
2674 .deviceId(stylusDeviceId)
2675 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2676 .x(50)
2677 .y(50))
2678 .build()));
2679 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2680
2681 // Finger down on the window
2682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2683 injectMotionEvent(mDispatcher,
2684 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2685 AINPUT_SOURCE_TOUCHSCREEN)
2686 .deviceId(touchDeviceId)
2687 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2688 .x(100)
2689 .y(100))
2690 .build()));
2691 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2692 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2693
2694 // Try to continue hovering with stylus. Since we are already down, injection should fail
2695 ASSERT_EQ(InputEventInjectionResult::FAILED,
2696 injectMotionEvent(mDispatcher,
2697 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2698 AINPUT_SOURCE_STYLUS)
2699 .deviceId(stylusDeviceId)
2700 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2701 .x(50)
2702 .y(50))
2703 .build()));
2704 // No event should be sent. This event should be ignored because a pointer from another device
2705 // is already down.
2706
2707 // Lift up the finger
2708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2709 injectMotionEvent(mDispatcher,
2710 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2711 AINPUT_SOURCE_TOUCHSCREEN)
2712 .deviceId(touchDeviceId)
2713 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2714 .x(100)
2715 .y(100))
2716 .build()));
2717 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2718
2719 // Now that the touch is gone, stylus hovering should start working again
2720 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2721 injectMotionEvent(mDispatcher,
2722 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2723 AINPUT_SOURCE_STYLUS)
2724 .deviceId(stylusDeviceId)
2725 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2726 .x(50)
2727 .y(50))
2728 .build()));
2729 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2730 // No more events
2731 window->assertNoEvents();
2732}
2733
2734/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002735 * A spy window above a window with no input channel.
2736 * Start hovering with a stylus device, and then tap with it.
2737 * Ensure spy window receives the entire sequence.
2738 */
2739TEST_F(InputDispatcherTest, StylusHoverAndDownNoInputChannel) {
2740 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2741 sp<FakeWindowHandle> spyWindow =
2742 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2743 spyWindow->setFrame(Rect(0, 0, 200, 200));
2744 spyWindow->setTrustedOverlay(true);
2745 spyWindow->setSpy(true);
2746 sp<FakeWindowHandle> window =
2747 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2748 window->setNoInputChannel(true);
2749 window->setFrame(Rect(0, 0, 200, 200));
2750
2751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2752
2753 NotifyMotionArgs args;
2754
2755 // Start hovering with stylus
2756 mDispatcher->notifyMotion(
2757 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2758 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2759 .build()));
2760 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2761 // Stop hovering
2762 mDispatcher->notifyMotion(
2763 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2764 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2765 .build()));
2766 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2767
2768 // Stylus touches down
2769 mDispatcher->notifyMotion(
2770 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_STYLUS)
2771 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2772 .build()));
2773 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2774
2775 // Stylus goes up
2776 mDispatcher->notifyMotion(
2777 &(args = MotionArgsBuilder(ACTION_UP, AINPUT_SOURCE_STYLUS)
2778 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2779 .build()));
2780 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_UP));
2781
2782 // Again hover
2783 mDispatcher->notifyMotion(
2784 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2785 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2786 .build()));
2787 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2788 // Stop hovering
2789 mDispatcher->notifyMotion(
2790 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2791 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2792 .build()));
2793 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2794
2795 // No more events
2796 spyWindow->assertNoEvents();
2797 window->assertNoEvents();
2798}
2799
2800/**
2801 * Start hovering with a mouse, and then tap with a touch device. Pilfer the touch stream.
2802 * Next, click with the mouse device. Both windows (spy and regular) should receive the new mouse
2803 * ACTION_DOWN event because that's a new gesture, and pilfering should no longer be active.
2804 * While the mouse is down, new move events from the touch device should be ignored.
2805 */
2806TEST_F(InputDispatcherTest, TouchPilferAndMouseMove) {
2807 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2808 sp<FakeWindowHandle> spyWindow =
2809 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2810 spyWindow->setFrame(Rect(0, 0, 200, 200));
2811 spyWindow->setTrustedOverlay(true);
2812 spyWindow->setSpy(true);
2813 sp<FakeWindowHandle> window =
2814 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2815 window->setFrame(Rect(0, 0, 200, 200));
2816
2817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2818
2819 const int32_t mouseDeviceId = 7;
2820 const int32_t touchDeviceId = 4;
2821 NotifyMotionArgs args;
2822
2823 // Hover a bit with mouse first
2824 mDispatcher->notifyMotion(&(
2825 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2826 .deviceId(mouseDeviceId)
2827 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2828 .build()));
2829 spyWindow->consumeMotionEvent(
2830 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2831 window->consumeMotionEvent(
2832 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2833
2834 // Start touching
2835 mDispatcher->notifyMotion(
2836 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2837 .deviceId(touchDeviceId)
2838 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2839 .build()));
2840 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2841 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2842 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2843 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2844
2845 mDispatcher->notifyMotion(
2846 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2847 .deviceId(touchDeviceId)
2848 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(55).y(55))
2849 .build()));
2850 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2851 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2852
2853 // Pilfer the stream
2854 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2855 window->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2856
2857 mDispatcher->notifyMotion(
2858 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2859 .deviceId(touchDeviceId)
2860 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
2861 .build()));
2862 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2863
2864 // Mouse down
2865 mDispatcher->notifyMotion(&(
2866 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2867 .deviceId(mouseDeviceId)
2868 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2869 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2870 .build()));
2871
2872 spyWindow->consumeMotionEvent(
2873 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId)));
2874 spyWindow->consumeMotionEvent(
2875 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2876 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2877
2878 mDispatcher->notifyMotion(&(
2879 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2880 .deviceId(mouseDeviceId)
2881 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2882 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2883 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2884 .build()));
2885 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2886 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2887
2888 // Mouse move!
2889 mDispatcher->notifyMotion(&(
2890 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_MOUSE)
2891 .deviceId(mouseDeviceId)
2892 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2893 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(110).y(110))
2894 .build()));
2895 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2896 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2897
2898 // Touch move!
2899 mDispatcher->notifyMotion(
2900 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2901 .deviceId(touchDeviceId)
2902 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(65).y(65))
2903 .build()));
2904
2905 // No more events
2906 spyWindow->assertNoEvents();
2907 window->assertNoEvents();
2908}
2909
2910/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002911 * On the display, have a single window, and also an area where there's no window.
2912 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2913 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2914 */
2915TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2917 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002918 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002919
2920 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2921 NotifyMotionArgs args;
2922
2923 // Touch down on the empty space
2924 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2925
2926 mDispatcher->waitForIdle();
2927 window->assertNoEvents();
2928
2929 // Now touch down on the window with another pointer
2930 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2931 mDispatcher->waitForIdle();
2932 window->consumeMotionDown();
2933}
2934
2935/**
2936 * Same test as above, but instead of touching the empty space, the first touch goes to
2937 * non-touchable window.
2938 */
2939TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2940 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2941 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002942 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002943 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2944 window1->setTouchable(false);
2945 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002946 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002947 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2948
2949 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2950
2951 NotifyMotionArgs args;
2952 // Touch down on the non-touchable window
2953 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2954
2955 mDispatcher->waitForIdle();
2956 window1->assertNoEvents();
2957 window2->assertNoEvents();
2958
2959 // Now touch down on the window with another pointer
2960 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2961 mDispatcher->waitForIdle();
2962 window2->consumeMotionDown();
2963}
2964
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002965/**
2966 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2967 * to the event time of the first ACTION_DOWN sent to the particular window.
2968 */
2969TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2970 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2971 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002972 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002973 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2974 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002975 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002976 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2977
2978 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2979
2980 NotifyMotionArgs args;
2981 // Touch down on the first window
2982 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2983
2984 mDispatcher->waitForIdle();
2985 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002986 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002987 window2->assertNoEvents();
2988 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2989 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2990 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2991
2992 // Now touch down on the window with another pointer
2993 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2994 mDispatcher->waitForIdle();
2995 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002996 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002997 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2998 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2999 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
3000 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
3001
3002 // Now move the pointer on the second window
3003 mDispatcher->notifyMotion(
3004 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
3005 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003006 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003007
3008 // Now add new touch down on the second window
3009 mDispatcher->notifyMotion(
3010 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
3011 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003012 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003013
3014 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
3015 window1->consumeMotionMove();
3016 window1->assertNoEvents();
3017
3018 // Now move the pointer on the first window
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08003019 mDispatcher->notifyMotion(&(
3020 args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}, {150, 50}})));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003021 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003022 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003023
3024 mDispatcher->notifyMotion(&(
3025 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
3026 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003027 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003028}
3029
Garfield Tandf26e862020-07-01 20:18:19 -07003030TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003031 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003032 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003033 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003034 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003035 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003036 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003037 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003038
3039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3040
3041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
3042
3043 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003045 injectMotionEvent(mDispatcher,
3046 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3047 AINPUT_SOURCE_MOUSE)
3048 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3049 .x(900)
3050 .y(400))
3051 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003052 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003053
3054 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003056 injectMotionEvent(mDispatcher,
3057 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3058 AINPUT_SOURCE_MOUSE)
3059 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3060 .x(300)
3061 .y(400))
3062 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003063 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3064 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003065
3066 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003068 injectMotionEvent(mDispatcher,
3069 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3070 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3071 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3072 .x(300)
3073 .y(400))
3074 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003075 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3076 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003077
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003079 injectMotionEvent(mDispatcher,
3080 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3081 AINPUT_SOURCE_MOUSE)
3082 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3083 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3084 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3085 .x(300)
3086 .y(400))
3087 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003088 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003089
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003091 injectMotionEvent(mDispatcher,
3092 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3093 AINPUT_SOURCE_MOUSE)
3094 .buttonState(0)
3095 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3096 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3097 .x(300)
3098 .y(400))
3099 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003100 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003103 injectMotionEvent(mDispatcher,
3104 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3105 .buttonState(0)
3106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3107 .x(300)
3108 .y(400))
3109 .build()));
3110 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3111
3112 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003114 injectMotionEvent(mDispatcher,
3115 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3116 AINPUT_SOURCE_MOUSE)
3117 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3118 .x(900)
3119 .y(400))
3120 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003121 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003122
3123 // No more events
3124 windowLeft->assertNoEvents();
3125 windowRight->assertNoEvents();
3126}
3127
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003128/**
3129 * Put two fingers down (and don't release them) and click the mouse button.
3130 * The clicking of mouse is a new ACTION_DOWN event. Since it's from a different device, the
3131 * currently active gesture should be canceled, and the new one should proceed.
3132 */
3133TEST_F(InputDispatcherTest, TwoPointersDownMouseClick) {
3134 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3135 sp<FakeWindowHandle> window =
3136 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3137 window->setFrame(Rect(0, 0, 600, 800));
3138
3139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3140
3141 const int32_t touchDeviceId = 4;
3142 const int32_t mouseDeviceId = 6;
3143 NotifyMotionArgs args;
3144
3145 // Two pointers down
3146 mDispatcher->notifyMotion(&(
3147 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3148 .deviceId(touchDeviceId)
3149 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3150 .build()));
3151
3152 mDispatcher->notifyMotion(&(
3153 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3154 .deviceId(touchDeviceId)
3155 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3156 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
3157 .build()));
3158 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
3159 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
3160
3161 // Inject a series of mouse events for a mouse click
3162 mDispatcher->notifyMotion(&(
3163 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3164 .deviceId(mouseDeviceId)
3165 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3166 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3167 .build()));
3168 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
3169 WithPointerCount(2u)));
3170 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
3171
3172 mDispatcher->notifyMotion(&(
3173 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
3174 .deviceId(mouseDeviceId)
3175 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3176 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3177 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3178 .build()));
3179 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
3180
3181 // Try to send more touch events while the mouse is down. Since it's a continuation of an
3182 // already canceled gesture, it should be ignored.
3183 mDispatcher->notifyMotion(&(
3184 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
3185 .deviceId(touchDeviceId)
3186 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(101).y(101))
3187 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(121).y(121))
3188 .build()));
3189 window->assertNoEvents();
3190}
3191
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003192TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
3193 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3194
3195 sp<FakeWindowHandle> spyWindow =
3196 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3197 spyWindow->setFrame(Rect(0, 0, 600, 800));
3198 spyWindow->setTrustedOverlay(true);
3199 spyWindow->setSpy(true);
3200 sp<FakeWindowHandle> window =
3201 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3202 window->setFrame(Rect(0, 0, 600, 800));
3203
3204 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3206
3207 // Send mouse cursor to the window
3208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3209 injectMotionEvent(mDispatcher,
3210 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3211 AINPUT_SOURCE_MOUSE)
3212 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3213 .x(100)
3214 .y(100))
3215 .build()));
3216
3217 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3218 WithSource(AINPUT_SOURCE_MOUSE)));
3219 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3220 WithSource(AINPUT_SOURCE_MOUSE)));
3221
3222 window->assertNoEvents();
3223 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003224}
3225
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003226TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
3227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3228
3229 sp<FakeWindowHandle> spyWindow =
3230 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3231 spyWindow->setFrame(Rect(0, 0, 600, 800));
3232 spyWindow->setTrustedOverlay(true);
3233 spyWindow->setSpy(true);
3234 sp<FakeWindowHandle> window =
3235 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3236 window->setFrame(Rect(0, 0, 600, 800));
3237
3238 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3240
3241 // Send mouse cursor to the window
3242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3243 injectMotionEvent(mDispatcher,
3244 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3245 AINPUT_SOURCE_MOUSE)
3246 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3247 .x(100)
3248 .y(100))
3249 .build()));
3250
3251 // Move mouse cursor
3252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3253 injectMotionEvent(mDispatcher,
3254 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3255 AINPUT_SOURCE_MOUSE)
3256 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3257 .x(110)
3258 .y(110))
3259 .build()));
3260
3261 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3262 WithSource(AINPUT_SOURCE_MOUSE)));
3263 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3264 WithSource(AINPUT_SOURCE_MOUSE)));
3265 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3266 WithSource(AINPUT_SOURCE_MOUSE)));
3267 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3268 WithSource(AINPUT_SOURCE_MOUSE)));
3269 // Touch down on the window
3270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3271 injectMotionEvent(mDispatcher,
3272 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3273 AINPUT_SOURCE_TOUCHSCREEN)
3274 .deviceId(SECOND_DEVICE_ID)
3275 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3276 .x(200)
3277 .y(200))
3278 .build()));
3279 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3280 WithSource(AINPUT_SOURCE_MOUSE)));
3281 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3282 WithSource(AINPUT_SOURCE_MOUSE)));
3283 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3284 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3285 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3286 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3287
3288 // pilfer the motion, retaining the gesture on the spy window.
3289 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
3290 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3291 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3292
3293 // Touch UP on the window
3294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3295 injectMotionEvent(mDispatcher,
3296 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3297 AINPUT_SOURCE_TOUCHSCREEN)
3298 .deviceId(SECOND_DEVICE_ID)
3299 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3300 .x(200)
3301 .y(200))
3302 .build()));
3303 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3304 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3305
3306 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
3307 // to send a new gesture. It should again go to both windows (spy and the window below), just
3308 // like the first gesture did, before pilfering. The window configuration has not changed.
3309
3310 // One more tap - DOWN
3311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3312 injectMotionEvent(mDispatcher,
3313 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3314 AINPUT_SOURCE_TOUCHSCREEN)
3315 .deviceId(SECOND_DEVICE_ID)
3316 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3317 .x(250)
3318 .y(250))
3319 .build()));
3320 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3321 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3322 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3323 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3324
3325 // Touch UP on the window
3326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3327 injectMotionEvent(mDispatcher,
3328 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3329 AINPUT_SOURCE_TOUCHSCREEN)
3330 .deviceId(SECOND_DEVICE_ID)
3331 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3332 .x(250)
3333 .y(250))
3334 .build()));
3335 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3336 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3337 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3338 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3339
3340 window->assertNoEvents();
3341 spyWindow->assertNoEvents();
3342}
3343
Garfield Tandf26e862020-07-01 20:18:19 -07003344// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
3345// directly in this test.
3346TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003347 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003348 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003349 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003350 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003351
3352 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3353
3354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3355
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003357 injectMotionEvent(mDispatcher,
3358 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3359 AINPUT_SOURCE_MOUSE)
3360 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3361 .x(300)
3362 .y(400))
3363 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003364 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003365 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003367 injectMotionEvent(mDispatcher,
3368 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3369 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3370 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3371 .x(300)
3372 .y(400))
3373 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003374 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3375 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003376
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003378 injectMotionEvent(mDispatcher,
3379 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3380 AINPUT_SOURCE_MOUSE)
3381 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3382 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3383 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3384 .x(300)
3385 .y(400))
3386 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003387 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003388
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003390 injectMotionEvent(mDispatcher,
3391 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3392 AINPUT_SOURCE_MOUSE)
3393 .buttonState(0)
3394 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3395 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3396 .x(300)
3397 .y(400))
3398 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003399 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003400
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003402 injectMotionEvent(mDispatcher,
3403 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3404 .buttonState(0)
3405 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3406 .x(300)
3407 .y(400))
3408 .build()));
3409 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3410
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003412 injectMotionEvent(mDispatcher,
3413 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
3414 AINPUT_SOURCE_MOUSE)
3415 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3416 .x(300)
3417 .y(400))
3418 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003419 window->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003420}
3421
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003422/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003423 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
3424 * is generated.
3425 */
3426TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
3427 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3428 sp<FakeWindowHandle> window =
3429 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3430 window->setFrame(Rect(0, 0, 1200, 800));
3431
3432 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3433
3434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3435
3436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3437 injectMotionEvent(mDispatcher,
3438 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3439 AINPUT_SOURCE_MOUSE)
3440 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3441 .x(300)
3442 .y(400))
3443 .build()));
3444 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3445
3446 // Remove the window, but keep the channel.
3447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3448 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3449}
3450
3451/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003452 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003453 * The tap causes a HOVER_EXIT event to be generated because the current event
3454 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003455 */
3456TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3457 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3458 sp<FakeWindowHandle> window =
3459 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3460 window->setFrame(Rect(0, 0, 100, 100));
3461
3462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3463
3464 // Inject a hover_move from mouse.
3465 NotifyMotionArgs motionArgs =
3466 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3467 ADISPLAY_ID_DEFAULT, {{50, 50}});
3468 motionArgs.xCursorPosition = 50;
3469 motionArgs.yCursorPosition = 50;
3470 mDispatcher->notifyMotion(&motionArgs);
3471 ASSERT_NO_FATAL_FAILURE(
3472 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3473 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003474
3475 // Tap on the window
3476 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3477 ADISPLAY_ID_DEFAULT, {{10, 10}});
3478 mDispatcher->notifyMotion(&motionArgs);
3479 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003480 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3481 WithSource(AINPUT_SOURCE_MOUSE))));
3482
3483 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003484 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3485 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3486
3487 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3488 ADISPLAY_ID_DEFAULT, {{10, 10}});
3489 mDispatcher->notifyMotion(&motionArgs);
3490 ASSERT_NO_FATAL_FAILURE(
3491 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3492 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3493}
3494
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003495TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3496 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3497 sp<FakeWindowHandle> windowDefaultDisplay =
3498 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3499 ADISPLAY_ID_DEFAULT);
3500 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3501 sp<FakeWindowHandle> windowSecondDisplay =
3502 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3503 SECOND_DISPLAY_ID);
3504 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3505
3506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3507 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3508
3509 // Set cursor position in window in default display and check that hover enter and move
3510 // events are generated.
3511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3512 injectMotionEvent(mDispatcher,
3513 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3514 AINPUT_SOURCE_MOUSE)
3515 .displayId(ADISPLAY_ID_DEFAULT)
3516 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3517 .x(300)
3518 .y(600))
3519 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003520 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003521
3522 // Remove all windows in secondary display and check that no event happens on window in
3523 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003524 mDispatcher->setInputWindows(
3525 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003526 windowDefaultDisplay->assertNoEvents();
3527
3528 // Move cursor position in window in default display and check that only hover move
3529 // event is generated and not hover enter event.
3530 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3531 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3533 injectMotionEvent(mDispatcher,
3534 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3535 AINPUT_SOURCE_MOUSE)
3536 .displayId(ADISPLAY_ID_DEFAULT)
3537 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3538 .x(400)
3539 .y(700))
3540 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003541 windowDefaultDisplay->consumeMotionEvent(
3542 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3543 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003544 windowDefaultDisplay->assertNoEvents();
3545}
3546
Garfield Tan00f511d2019-06-12 16:55:40 -07003547TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003548 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003549
3550 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003551 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003552 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003553 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003554 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003555 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003556
3557 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3558
Arthur Hung72d8dc32020-03-28 00:48:39 +00003559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003560
3561 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3562 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003564 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003565 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003566 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003567 windowRight->assertNoEvents();
3568}
3569
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003570TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003572 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3573 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003574 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003575
Arthur Hung72d8dc32020-03-28 00:48:39 +00003576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003577 setFocusedWindow(window);
3578
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003579 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003580
3581 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3582 mDispatcher->notifyKey(&keyArgs);
3583
3584 // Window should receive key down event.
3585 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3586
3587 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3588 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003589 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003590 mDispatcher->notifyDeviceReset(&args);
3591 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3592 AKEY_EVENT_FLAG_CANCELED);
3593}
3594
3595TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003596 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003597 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3598 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003599
Arthur Hung72d8dc32020-03-28 00:48:39 +00003600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003601
3602 NotifyMotionArgs motionArgs =
3603 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3604 ADISPLAY_ID_DEFAULT);
3605 mDispatcher->notifyMotion(&motionArgs);
3606
3607 // Window should receive motion down event.
3608 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3609
3610 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3611 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003612 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003613 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003614 window->consumeMotionEvent(
3615 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003616}
3617
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003618TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003620 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3621 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003622 window->setFocusable(true);
3623
3624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3625 setFocusedWindow(window);
3626
3627 window->consumeFocusEvent(true);
3628
3629 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3630 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3631 const nsecs_t injectTime = keyArgs.eventTime;
3632 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3633 mDispatcher->notifyKey(&keyArgs);
3634 // The dispatching time should be always greater than or equal to intercept key timeout.
3635 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3636 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3637 std::chrono::nanoseconds(interceptKeyTimeout).count());
3638}
3639
3640TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3641 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003642 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3643 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003644 window->setFocusable(true);
3645
3646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3647 setFocusedWindow(window);
3648
3649 window->consumeFocusEvent(true);
3650
3651 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3652 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3653 mFakePolicy->setInterceptKeyTimeout(150ms);
3654 mDispatcher->notifyKey(&keyDown);
3655 mDispatcher->notifyKey(&keyUp);
3656
3657 // Window should receive key event immediately when same key up.
3658 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3659 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3660}
3661
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003662/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003663 * Two windows. First is a regular window. Second does not overlap with the first, and has
3664 * WATCH_OUTSIDE_TOUCH.
3665 * Both windows are owned by the same UID.
3666 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3667 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3668 */
3669TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3670 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3671 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3672 "First Window", ADISPLAY_ID_DEFAULT);
3673 window->setFrame(Rect{0, 0, 100, 100});
3674
3675 sp<FakeWindowHandle> outsideWindow =
3676 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3677 ADISPLAY_ID_DEFAULT);
3678 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3679 outsideWindow->setWatchOutsideTouch(true);
3680 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3682
3683 // Tap on first window.
3684 NotifyMotionArgs motionArgs =
3685 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3686 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3687 mDispatcher->notifyMotion(&motionArgs);
3688 window->consumeMotionDown();
3689 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3690 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3691 outsideWindow->consumeMotionEvent(
3692 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3693}
3694
3695/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003696 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3697 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3698 * ACTION_OUTSIDE event is sent per gesture.
3699 */
3700TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3701 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3702 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003703 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3704 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003705 window->setWatchOutsideTouch(true);
3706 window->setFrame(Rect{0, 0, 100, 100});
3707 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003708 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3709 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003710 secondWindow->setFrame(Rect{100, 100, 200, 200});
3711 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003712 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3713 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003714 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3716
3717 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3718 NotifyMotionArgs motionArgs =
3719 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3720 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3721 mDispatcher->notifyMotion(&motionArgs);
3722 window->assertNoEvents();
3723 secondWindow->assertNoEvents();
3724
3725 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3726 // Now, `window` should get ACTION_OUTSIDE.
3727 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3728 {PointF{-10, -10}, PointF{105, 105}});
3729 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003730 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3731 window->consumeMotionEvent(
3732 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003733 secondWindow->consumeMotionDown();
3734 thirdWindow->assertNoEvents();
3735
3736 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3737 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3738 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3739 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3740 mDispatcher->notifyMotion(&motionArgs);
3741 window->assertNoEvents();
3742 secondWindow->consumeMotionMove();
3743 thirdWindow->consumeMotionDown();
3744}
3745
Prabir Pradhan814fe082022-07-22 20:22:18 +00003746TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003748 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3749 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003750 window->setFocusable(true);
3751
3752 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3753 setFocusedWindow(window);
3754
3755 window->consumeFocusEvent(true);
3756
3757 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3758 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3759 mDispatcher->notifyKey(&keyDown);
3760 mDispatcher->notifyKey(&keyUp);
3761
3762 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3763 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3764
3765 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3766 mDispatcher->onWindowInfosChanged({}, {});
3767
3768 window->consumeFocusEvent(false);
3769
3770 mDispatcher->notifyKey(&keyDown);
3771 mDispatcher->notifyKey(&keyUp);
3772 window->assertNoEvents();
3773}
3774
Arthur Hung96483742022-11-15 03:30:48 +00003775TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3776 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3777 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3778 "Fake Window", ADISPLAY_ID_DEFAULT);
3779 // Ensure window is non-split and have some transform.
3780 window->setPreventSplitting(true);
3781 window->setWindowOffset(20, 40);
3782 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3783
3784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3785 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3786 {50, 50}))
3787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3788 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3789
3790 const MotionEvent secondFingerDownEvent =
3791 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3792 .displayId(ADISPLAY_ID_DEFAULT)
3793 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003794 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3795 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003796 .build();
3797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3798 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3799 InputEventInjectionSync::WAIT_FOR_RESULT))
3800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3801
3802 const MotionEvent* event = window->consumeMotion();
3803 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3804 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3805 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3806 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3807 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3808}
3809
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003810/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003811 * Ensure the correct coordinate spaces are used by InputDispatcher.
3812 *
3813 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3814 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3815 * space.
3816 */
3817class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3818public:
3819 void SetUp() override {
3820 InputDispatcherTest::SetUp();
3821 mDisplayInfos.clear();
3822 mWindowInfos.clear();
3823 }
3824
3825 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3826 gui::DisplayInfo info;
3827 info.displayId = displayId;
3828 info.transform = transform;
3829 mDisplayInfos.push_back(std::move(info));
3830 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3831 }
3832
3833 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3834 mWindowInfos.push_back(*windowHandle->getInfo());
3835 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3836 }
3837
3838 // Set up a test scenario where the display has a scaled projection and there are two windows
3839 // on the display.
3840 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3841 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3842 // respectively.
3843 ui::Transform displayTransform;
3844 displayTransform.set(2, 0, 0, 4);
3845 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3846
3847 std::shared_ptr<FakeApplicationHandle> application =
3848 std::make_shared<FakeApplicationHandle>();
3849
3850 // Add two windows to the display. Their frames are represented in the display space.
3851 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003852 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3853 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003854 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3855 addWindow(firstWindow);
3856
3857 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003858 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3859 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003860 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3861 addWindow(secondWindow);
3862 return {std::move(firstWindow), std::move(secondWindow)};
3863 }
3864
3865private:
3866 std::vector<gui::DisplayInfo> mDisplayInfos;
3867 std::vector<gui::WindowInfo> mWindowInfos;
3868};
3869
3870TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3871 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3872 // Send down to the first window. The point is represented in the display space. The point is
3873 // selected so that if the hit test was done with the transform applied to it, then it would
3874 // end up in the incorrect window.
3875 NotifyMotionArgs downMotionArgs =
3876 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3877 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3878 mDispatcher->notifyMotion(&downMotionArgs);
3879
3880 firstWindow->consumeMotionDown();
3881 secondWindow->assertNoEvents();
3882}
3883
3884// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3885// the event should be treated as being in the logical display space.
3886TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3887 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3888 // Send down to the first window. The point is represented in the logical display space. The
3889 // point is selected so that if the hit test was done in logical display space, then it would
3890 // end up in the incorrect window.
3891 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3892 PointF{75 * 2, 55 * 4});
3893
3894 firstWindow->consumeMotionDown();
3895 secondWindow->assertNoEvents();
3896}
3897
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003898// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3899// event should be treated as being in the logical display space.
3900TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3901 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3902
3903 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3904 ui::Transform injectedEventTransform;
3905 injectedEventTransform.set(matrix);
3906 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
3907 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
3908
3909 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3910 .displayId(ADISPLAY_ID_DEFAULT)
3911 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003912 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003913 .x(untransformedPoint.x)
3914 .y(untransformedPoint.y))
3915 .build();
3916 event.transform(matrix);
3917
3918 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
3919 InputEventInjectionSync::WAIT_FOR_RESULT);
3920
3921 firstWindow->consumeMotionDown();
3922 secondWindow->assertNoEvents();
3923}
3924
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003925TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
3926 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3927
3928 // Send down to the second window.
3929 NotifyMotionArgs downMotionArgs =
3930 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3931 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
3932 mDispatcher->notifyMotion(&downMotionArgs);
3933
3934 firstWindow->assertNoEvents();
3935 const MotionEvent* event = secondWindow->consumeMotion();
3936 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
3937
3938 // Ensure that the events from the "getRaw" API are in logical display coordinates.
3939 EXPECT_EQ(300, event->getRawX(0));
3940 EXPECT_EQ(880, event->getRawY(0));
3941
3942 // Ensure that the x and y values are in the window's coordinate space.
3943 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
3944 // the logical display space. This will be the origin of the window space.
3945 EXPECT_EQ(100, event->getX(0));
3946 EXPECT_EQ(80, event->getY(0));
3947}
3948
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003949using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
3950 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003951
3952class TransferTouchFixture : public InputDispatcherTest,
3953 public ::testing::WithParamInterface<TransferFunction> {};
3954
3955TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07003956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003957
3958 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003959 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003960 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3961 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003962 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003963 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003964 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3965 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003966 sp<FakeWindowHandle> wallpaper =
3967 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
3968 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003969 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00003970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003971
3972 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003973 NotifyMotionArgs downMotionArgs =
3974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3975 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003976 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003977
Svet Ganov5d3bc372020-01-26 23:11:07 -08003978 // Only the first window should get the down event
3979 firstWindow->consumeMotionDown();
3980 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003981 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003982
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003983 // Transfer touch to the second window
3984 TransferFunction f = GetParam();
3985 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3986 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003987 // The first window gets cancel and the second gets down
3988 firstWindow->consumeMotionCancel();
3989 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003990 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003991
3992 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003993 NotifyMotionArgs upMotionArgs =
3994 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3995 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003996 mDispatcher->notifyMotion(&upMotionArgs);
3997 // The first window gets no events and the second gets up
3998 firstWindow->assertNoEvents();
3999 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004000 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004001}
4002
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004003/**
4004 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4005 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4006 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4007 * natural to the user.
4008 * In this test, we are sending a pointer to both spy window and first window. We then try to
4009 * transfer touch to the second window. The dispatcher should identify the first window as the
4010 * one that should lose the gesture, and therefore the action should be to move the gesture from
4011 * the first window to the second.
4012 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4013 * the other API, as well.
4014 */
4015TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4016 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4017
4018 // Create a couple of windows + a spy window
4019 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004020 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004021 spyWindow->setTrustedOverlay(true);
4022 spyWindow->setSpy(true);
4023 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004024 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004025 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004026 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004027
4028 // Add the windows to the dispatcher
4029 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4030
4031 // Send down to the first window
4032 NotifyMotionArgs downMotionArgs =
4033 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4034 ADISPLAY_ID_DEFAULT);
4035 mDispatcher->notifyMotion(&downMotionArgs);
4036 // Only the first window and spy should get the down event
4037 spyWindow->consumeMotionDown();
4038 firstWindow->consumeMotionDown();
4039
4040 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4041 // if f === 'transferTouch'.
4042 TransferFunction f = GetParam();
4043 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4044 ASSERT_TRUE(success);
4045 // The first window gets cancel and the second gets down
4046 firstWindow->consumeMotionCancel();
4047 secondWindow->consumeMotionDown();
4048
4049 // Send up event to the second window
4050 NotifyMotionArgs upMotionArgs =
4051 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4052 ADISPLAY_ID_DEFAULT);
4053 mDispatcher->notifyMotion(&upMotionArgs);
4054 // The first window gets no events and the second+spy get up
4055 firstWindow->assertNoEvents();
4056 spyWindow->consumeMotionUp();
4057 secondWindow->consumeMotionUp();
4058}
4059
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004060TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004061 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004062
4063 PointF touchPoint = {10, 10};
4064
4065 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004066 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004067 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4068 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004069 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004070 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004071 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4072 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004073 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004074
4075 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004076 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004077
4078 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004079 NotifyMotionArgs downMotionArgs =
4080 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4081 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004082 mDispatcher->notifyMotion(&downMotionArgs);
4083 // Only the first window should get the down event
4084 firstWindow->consumeMotionDown();
4085 secondWindow->assertNoEvents();
4086
4087 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004088 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004089 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004090 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4092 // Only the first window should get the pointer down event
4093 firstWindow->consumeMotionPointerDown(1);
4094 secondWindow->assertNoEvents();
4095
4096 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004097 TransferFunction f = GetParam();
4098 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4099 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100 // The first window gets cancel and the second gets down and pointer down
4101 firstWindow->consumeMotionCancel();
4102 secondWindow->consumeMotionDown();
4103 secondWindow->consumeMotionPointerDown(1);
4104
4105 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004106 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004107 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004108 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004109 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4110 // The first window gets nothing and the second gets pointer up
4111 firstWindow->assertNoEvents();
4112 secondWindow->consumeMotionPointerUp(1);
4113
4114 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004115 NotifyMotionArgs upMotionArgs =
4116 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4117 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004118 mDispatcher->notifyMotion(&upMotionArgs);
4119 // The first window gets nothing and the second gets up
4120 firstWindow->assertNoEvents();
4121 secondWindow->consumeMotionUp();
4122}
4123
Arthur Hungc539dbb2022-12-08 07:45:36 +00004124TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4126
4127 // Create a couple of windows
4128 sp<FakeWindowHandle> firstWindow =
4129 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4130 ADISPLAY_ID_DEFAULT);
4131 firstWindow->setDupTouchToWallpaper(true);
4132 sp<FakeWindowHandle> secondWindow =
4133 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4134 ADISPLAY_ID_DEFAULT);
4135 secondWindow->setDupTouchToWallpaper(true);
4136
4137 sp<FakeWindowHandle> wallpaper1 =
4138 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4139 wallpaper1->setIsWallpaper(true);
4140
4141 sp<FakeWindowHandle> wallpaper2 =
4142 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4143 wallpaper2->setIsWallpaper(true);
4144 // Add the windows to the dispatcher
4145 mDispatcher->setInputWindows(
4146 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4147
4148 // Send down to the first window
4149 NotifyMotionArgs downMotionArgs =
4150 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4151 ADISPLAY_ID_DEFAULT);
4152 mDispatcher->notifyMotion(&downMotionArgs);
4153
4154 // Only the first window should get the down event
4155 firstWindow->consumeMotionDown();
4156 secondWindow->assertNoEvents();
4157 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4158 wallpaper2->assertNoEvents();
4159
4160 // Transfer touch focus to the second window
4161 TransferFunction f = GetParam();
4162 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4163 ASSERT_TRUE(success);
4164
4165 // The first window gets cancel and the second gets down
4166 firstWindow->consumeMotionCancel();
4167 secondWindow->consumeMotionDown();
4168 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4169 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4170
4171 // Send up event to the second window
4172 NotifyMotionArgs upMotionArgs =
4173 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4174 ADISPLAY_ID_DEFAULT);
4175 mDispatcher->notifyMotion(&upMotionArgs);
4176 // The first window gets no events and the second gets up
4177 firstWindow->assertNoEvents();
4178 secondWindow->consumeMotionUp();
4179 wallpaper1->assertNoEvents();
4180 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4181}
4182
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004183// For the cases of single pointer touch and two pointers non-split touch, the api's
4184// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4185// for the case where there are multiple pointers split across several windows.
4186INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4187 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004188 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4189 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004190 return dispatcher->transferTouch(destChannelToken,
4191 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004192 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004193 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4194 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004195 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004196 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004197 }));
4198
Svet Ganov5d3bc372020-01-26 23:11:07 -08004199TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004200 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004202 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004203 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4204 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004206
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004207 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004208 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4209 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004210 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211
4212 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004214
4215 PointF pointInFirst = {300, 200};
4216 PointF pointInSecond = {300, 600};
4217
4218 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004219 NotifyMotionArgs firstDownMotionArgs =
4220 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4221 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004222 mDispatcher->notifyMotion(&firstDownMotionArgs);
4223 // Only the first window should get the down event
4224 firstWindow->consumeMotionDown();
4225 secondWindow->assertNoEvents();
4226
4227 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004228 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004229 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004230 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004231 mDispatcher->notifyMotion(&secondDownMotionArgs);
4232 // The first window gets a move and the second a down
4233 firstWindow->consumeMotionMove();
4234 secondWindow->consumeMotionDown();
4235
4236 // Transfer touch focus to the second window
4237 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4238 // The first window gets cancel and the new gets pointer down (it already saw down)
4239 firstWindow->consumeMotionCancel();
4240 secondWindow->consumeMotionPointerDown(1);
4241
4242 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004243 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004244 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004245 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4247 // The first window gets nothing and the second gets pointer up
4248 firstWindow->assertNoEvents();
4249 secondWindow->consumeMotionPointerUp(1);
4250
4251 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004252 NotifyMotionArgs upMotionArgs =
4253 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4254 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004255 mDispatcher->notifyMotion(&upMotionArgs);
4256 // The first window gets nothing and the second gets up
4257 firstWindow->assertNoEvents();
4258 secondWindow->consumeMotionUp();
4259}
4260
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004261// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4262// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4263// touch is not supported, so the touch should continue on those windows and the transferred-to
4264// window should get nothing.
4265TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4266 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4267
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004268 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004269 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4270 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004271 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004272
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004273 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004274 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4275 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004276 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004277
4278 // Add the windows to the dispatcher
4279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4280
4281 PointF pointInFirst = {300, 200};
4282 PointF pointInSecond = {300, 600};
4283
4284 // Send down to the first window
4285 NotifyMotionArgs firstDownMotionArgs =
4286 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4287 ADISPLAY_ID_DEFAULT, {pointInFirst});
4288 mDispatcher->notifyMotion(&firstDownMotionArgs);
4289 // Only the first window should get the down event
4290 firstWindow->consumeMotionDown();
4291 secondWindow->assertNoEvents();
4292
4293 // Send down to the second window
4294 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004295 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004296 {pointInFirst, pointInSecond});
4297 mDispatcher->notifyMotion(&secondDownMotionArgs);
4298 // The first window gets a move and the second a down
4299 firstWindow->consumeMotionMove();
4300 secondWindow->consumeMotionDown();
4301
4302 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004303 const bool transferred =
4304 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004305 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4306 ASSERT_FALSE(transferred);
4307 firstWindow->assertNoEvents();
4308 secondWindow->assertNoEvents();
4309
4310 // The rest of the dispatch should proceed as normal
4311 // Send pointer up to the second window
4312 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004313 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004314 {pointInFirst, pointInSecond});
4315 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4316 // The first window gets MOVE and the second gets pointer up
4317 firstWindow->consumeMotionMove();
4318 secondWindow->consumeMotionUp();
4319
4320 // Send up event to the first window
4321 NotifyMotionArgs upMotionArgs =
4322 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4323 ADISPLAY_ID_DEFAULT);
4324 mDispatcher->notifyMotion(&upMotionArgs);
4325 // The first window gets nothing and the second gets up
4326 firstWindow->consumeMotionUp();
4327 secondWindow->assertNoEvents();
4328}
4329
Arthur Hungabbb9d82021-09-01 14:52:30 +00004330// This case will create two windows and one mirrored window on the default display and mirror
4331// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4332// the windows info of second display before default display.
4333TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4334 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4335 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004336 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004337 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004338 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004339 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004340 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004341
4342 sp<FakeWindowHandle> mirrorWindowInPrimary =
4343 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4344 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004345
4346 sp<FakeWindowHandle> firstWindowInSecondary =
4347 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4348 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004349
4350 sp<FakeWindowHandle> secondWindowInSecondary =
4351 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4352 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004353
4354 // Update window info, let it find window handle of second display first.
4355 mDispatcher->setInputWindows(
4356 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4357 {ADISPLAY_ID_DEFAULT,
4358 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4359
4360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4361 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4362 {50, 50}))
4363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4364
4365 // Window should receive motion event.
4366 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4367
4368 // Transfer touch focus
4369 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4370 secondWindowInPrimary->getToken()));
4371 // The first window gets cancel.
4372 firstWindowInPrimary->consumeMotionCancel();
4373 secondWindowInPrimary->consumeMotionDown();
4374
4375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4376 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4377 ADISPLAY_ID_DEFAULT, {150, 50}))
4378 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4379 firstWindowInPrimary->assertNoEvents();
4380 secondWindowInPrimary->consumeMotionMove();
4381
4382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4383 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4384 {150, 50}))
4385 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4386 firstWindowInPrimary->assertNoEvents();
4387 secondWindowInPrimary->consumeMotionUp();
4388}
4389
4390// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4391// 'transferTouch' api.
4392TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4393 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4394 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004395 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004396 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004397 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004398 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004399 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004400
4401 sp<FakeWindowHandle> mirrorWindowInPrimary =
4402 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4403 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004404
4405 sp<FakeWindowHandle> firstWindowInSecondary =
4406 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4407 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004408
4409 sp<FakeWindowHandle> secondWindowInSecondary =
4410 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4411 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004412
4413 // Update window info, let it find window handle of second display first.
4414 mDispatcher->setInputWindows(
4415 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4416 {ADISPLAY_ID_DEFAULT,
4417 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4418
4419 // Touch on second display.
4420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4421 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4422 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4423
4424 // Window should receive motion event.
4425 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4426
4427 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004428 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004429
4430 // The first window gets cancel.
4431 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4432 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4433
4434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4435 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4436 SECOND_DISPLAY_ID, {150, 50}))
4437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4438 firstWindowInPrimary->assertNoEvents();
4439 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4440
4441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4442 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4444 firstWindowInPrimary->assertNoEvents();
4445 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4446}
4447
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004448TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004450 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4451 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004452
Vishnu Nair47074b82020-08-14 11:54:47 -07004453 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004455 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004456
4457 window->consumeFocusEvent(true);
4458
4459 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4460 mDispatcher->notifyKey(&keyArgs);
4461
4462 // Window should receive key down event.
4463 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4464}
4465
4466TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004467 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004468 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4469 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004470
Arthur Hung72d8dc32020-03-28 00:48:39 +00004471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004472
4473 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4474 mDispatcher->notifyKey(&keyArgs);
4475 mDispatcher->waitForIdle();
4476
4477 window->assertNoEvents();
4478}
4479
4480// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4481TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004482 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004483 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4484 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004485
Arthur Hung72d8dc32020-03-28 00:48:39 +00004486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004487
4488 // Send key
4489 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4490 mDispatcher->notifyKey(&keyArgs);
4491 // Send motion
4492 NotifyMotionArgs motionArgs =
4493 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4494 ADISPLAY_ID_DEFAULT);
4495 mDispatcher->notifyMotion(&motionArgs);
4496
4497 // Window should receive only the motion event
4498 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4499 window->assertNoEvents(); // Key event or focus event will not be received
4500}
4501
arthurhungea3f4fc2020-12-21 23:18:53 +08004502TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4504
arthurhungea3f4fc2020-12-21 23:18:53 +08004505 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004506 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4507 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004508 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004509
arthurhungea3f4fc2020-12-21 23:18:53 +08004510 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004511 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4512 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004513 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004514
4515 // Add the windows to the dispatcher
4516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4517
4518 PointF pointInFirst = {300, 200};
4519 PointF pointInSecond = {300, 600};
4520
4521 // Send down to the first window
4522 NotifyMotionArgs firstDownMotionArgs =
4523 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4524 ADISPLAY_ID_DEFAULT, {pointInFirst});
4525 mDispatcher->notifyMotion(&firstDownMotionArgs);
4526 // Only the first window should get the down event
4527 firstWindow->consumeMotionDown();
4528 secondWindow->assertNoEvents();
4529
4530 // Send down to the second window
4531 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004532 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004533 {pointInFirst, pointInSecond});
4534 mDispatcher->notifyMotion(&secondDownMotionArgs);
4535 // The first window gets a move and the second a down
4536 firstWindow->consumeMotionMove();
4537 secondWindow->consumeMotionDown();
4538
4539 // Send pointer cancel to the second window
4540 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004541 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004542 {pointInFirst, pointInSecond});
4543 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4544 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4545 // The first window gets move and the second gets cancel.
4546 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4547 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4548
4549 // Send up event.
4550 NotifyMotionArgs upMotionArgs =
4551 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4552 ADISPLAY_ID_DEFAULT);
4553 mDispatcher->notifyMotion(&upMotionArgs);
4554 // The first window gets up and the second gets nothing.
4555 firstWindow->consumeMotionUp();
4556 secondWindow->assertNoEvents();
4557}
4558
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004559TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4561
4562 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004563 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4565 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4566 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4567 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4568
Harry Cutts33476232023-01-30 19:57:29 +00004569 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004570 window->assertNoEvents();
4571 mDispatcher->waitForIdle();
4572}
4573
chaviwd1c23182019-12-20 18:44:56 -08004574class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004575public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004576 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004577 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004578 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004579 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004580 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004581 }
4582
chaviwd1c23182019-12-20 18:44:56 -08004583 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4584
4585 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4586 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4587 expectedDisplayId, expectedFlags);
4588 }
4589
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004590 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4591
4592 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4593
chaviwd1c23182019-12-20 18:44:56 -08004594 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4595 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4596 expectedDisplayId, expectedFlags);
4597 }
4598
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004599 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4600 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4601 expectedDisplayId, expectedFlags);
4602 }
4603
chaviwd1c23182019-12-20 18:44:56 -08004604 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4605 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4606 expectedDisplayId, expectedFlags);
4607 }
4608
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004609 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004610 mInputReceiver->consumeMotionEvent(
4611 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4612 WithDisplayId(expectedDisplayId),
4613 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004614 }
4615
Arthur Hungfbfa5722021-11-16 02:45:54 +00004616 void consumeMotionPointerDown(int32_t pointerIdx) {
4617 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4618 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4619 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004620 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004621 }
4622
Evan Rosky84f07f02021-04-16 10:42:42 -07004623 MotionEvent* consumeMotion() {
4624 InputEvent* event = mInputReceiver->consume();
4625 if (!event) {
4626 ADD_FAILURE() << "No event was produced";
4627 return nullptr;
4628 }
4629 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4630 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4631 return nullptr;
4632 }
4633 return static_cast<MotionEvent*>(event);
4634 }
4635
chaviwd1c23182019-12-20 18:44:56 -08004636 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4637
4638private:
4639 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004640};
4641
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004642using InputDispatcherMonitorTest = InputDispatcherTest;
4643
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004644/**
4645 * Two entities that receive touch: A window, and a global monitor.
4646 * The touch goes to the window, and then the window disappears.
4647 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4648 * for the monitor, as well.
4649 * 1. foregroundWindow
4650 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4651 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004652TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004653 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4654 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004655 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004656
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004657 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004658
4659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4661 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4662 {100, 200}))
4663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4664
4665 // Both the foreground window and the global monitor should receive the touch down
4666 window->consumeMotionDown();
4667 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4668
4669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4670 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4671 ADISPLAY_ID_DEFAULT, {110, 200}))
4672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4673
4674 window->consumeMotionMove();
4675 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4676
4677 // Now the foreground window goes away
4678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4679 window->consumeMotionCancel();
4680 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4681
4682 // If more events come in, there will be no more foreground window to send them to. This will
4683 // cause a cancel for the monitor, as well.
4684 ASSERT_EQ(InputEventInjectionResult::FAILED,
4685 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4686 ADISPLAY_ID_DEFAULT, {120, 200}))
4687 << "Injection should fail because the window was removed";
4688 window->assertNoEvents();
4689 // Global monitor now gets the cancel
4690 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4691}
4692
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004693TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004694 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004695 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4696 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004698
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004699 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004700
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004703 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004704 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004705 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004706}
4707
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004708TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4709 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004710
Chris Yea209fde2020-07-22 13:54:51 -07004711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004712 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4713 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004715
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004717 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004718 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004719 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004720 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004721
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004722 // Pilfer pointers from the monitor.
4723 // This should not do anything and the window should continue to receive events.
4724 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004727 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4728 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004729 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004730
4731 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4732 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004733}
4734
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004735TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004736 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004737 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4738 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4740 window->setWindowOffset(20, 40);
4741 window->setWindowTransform(0, 1, -1, 0);
4742
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004743 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004744
4745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4746 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4747 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4748 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4749 MotionEvent* event = monitor.consumeMotion();
4750 // Even though window has transform, gesture monitor must not.
4751 ASSERT_EQ(ui::Transform(), event->getTransform());
4752}
4753
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004754TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004756 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004757
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004758 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004759 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004760 << "Injection should fail if there is a monitor, but no touchable window";
4761 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004762}
4763
chaviw81e2bb92019-12-18 15:03:51 -08004764TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004765 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004766 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4767 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004768
Arthur Hung72d8dc32020-03-28 00:48:39 +00004769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004770
4771 NotifyMotionArgs motionArgs =
4772 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4773 ADISPLAY_ID_DEFAULT);
4774
4775 mDispatcher->notifyMotion(&motionArgs);
4776 // Window should receive motion down event.
4777 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4778
4779 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004780 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004781 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4782 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4783 motionArgs.pointerCoords[0].getX() - 10);
4784
4785 mDispatcher->notifyMotion(&motionArgs);
4786 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004787 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004788}
4789
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004790/**
4791 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4792 * the device default right away. In the test scenario, we check both the default value,
4793 * and the action of enabling / disabling.
4794 */
4795TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004797 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4798 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004799 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004800
4801 // Set focused application.
4802 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004803 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004804
4805 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004807 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004808 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004809
4810 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004811 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004813 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004814
4815 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004816 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004817 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004818 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004819 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004821 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004822 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004823
4824 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004825 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004827 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004828
4829 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004830 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004831 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004832 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004833 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004835 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004836 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004837
4838 window->assertNoEvents();
4839}
4840
Gang Wange9087892020-01-07 12:17:14 -05004841TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004842 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004843 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4844 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004845
4846 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004847 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004848
Arthur Hung72d8dc32020-03-28 00:48:39 +00004849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004850 setFocusedWindow(window);
4851
Harry Cutts33476232023-01-30 19:57:29 +00004852 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004853
4854 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4855 mDispatcher->notifyKey(&keyArgs);
4856
4857 InputEvent* event = window->consume();
4858 ASSERT_NE(event, nullptr);
4859
4860 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4861 ASSERT_NE(verified, nullptr);
4862 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4863
4864 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4865 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4866 ASSERT_EQ(keyArgs.source, verified->source);
4867 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4868
4869 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4870
4871 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004872 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004873 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004874 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4875 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4876 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4877 ASSERT_EQ(0, verifiedKey.repeatCount);
4878}
4879
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004880TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004881 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004882 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4883 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004884
4885 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4886
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004887 ui::Transform transform;
4888 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4889
4890 gui::DisplayInfo displayInfo;
4891 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
4892 displayInfo.transform = transform;
4893
4894 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004895
4896 NotifyMotionArgs motionArgs =
4897 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4898 ADISPLAY_ID_DEFAULT);
4899 mDispatcher->notifyMotion(&motionArgs);
4900
4901 InputEvent* event = window->consume();
4902 ASSERT_NE(event, nullptr);
4903
4904 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4905 ASSERT_NE(verified, nullptr);
4906 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
4907
4908 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
4909 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
4910 EXPECT_EQ(motionArgs.source, verified->source);
4911 EXPECT_EQ(motionArgs.displayId, verified->displayId);
4912
4913 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
4914
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004915 const vec2 rawXY =
4916 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
4917 motionArgs.pointerCoords[0].getXYValue());
4918 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
4919 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004920 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004921 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004922 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004923 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
4924 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
4925}
4926
chaviw09c8d2d2020-08-24 15:48:26 -07004927/**
4928 * Ensure that separate calls to sign the same data are generating the same key.
4929 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
4930 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
4931 * tests.
4932 */
4933TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
4934 KeyEvent event = getTestKeyEvent();
4935 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4936
4937 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
4938 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
4939 ASSERT_EQ(hmac1, hmac2);
4940}
4941
4942/**
4943 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
4944 */
4945TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
4946 KeyEvent event = getTestKeyEvent();
4947 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4948 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
4949
4950 verifiedEvent.deviceId += 1;
4951 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4952
4953 verifiedEvent.source += 1;
4954 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4955
4956 verifiedEvent.eventTimeNanos += 1;
4957 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4958
4959 verifiedEvent.displayId += 1;
4960 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4961
4962 verifiedEvent.action += 1;
4963 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4964
4965 verifiedEvent.downTimeNanos += 1;
4966 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4967
4968 verifiedEvent.flags += 1;
4969 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4970
4971 verifiedEvent.keyCode += 1;
4972 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4973
4974 verifiedEvent.scanCode += 1;
4975 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4976
4977 verifiedEvent.metaState += 1;
4978 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4979
4980 verifiedEvent.repeatCount += 1;
4981 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4982}
4983
Vishnu Nair958da932020-08-21 17:12:37 -07004984TEST_F(InputDispatcherTest, SetFocusedWindow) {
4985 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4986 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004987 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004988 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004989 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004990 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4991
4992 // Top window is also focusable but is not granted focus.
4993 windowTop->setFocusable(true);
4994 windowSecond->setFocusable(true);
4995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4996 setFocusedWindow(windowSecond);
4997
4998 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5000 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005001
5002 // Focused window should receive event.
5003 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5004 windowTop->assertNoEvents();
5005}
5006
5007TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5008 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5009 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005010 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005011 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5012
5013 window->setFocusable(true);
5014 // Release channel for window is no longer valid.
5015 window->releaseChannel();
5016 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5017 setFocusedWindow(window);
5018
5019 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005020 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5021 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005022
5023 // window channel is invalid, so it should not receive any input event.
5024 window->assertNoEvents();
5025}
5026
5027TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5028 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5029 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005030 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005031 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005032 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5033
Vishnu Nair958da932020-08-21 17:12:37 -07005034 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5035 setFocusedWindow(window);
5036
5037 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005038 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5039 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005040
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005041 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005042 window->assertNoEvents();
5043}
5044
5045TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5046 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5047 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005048 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005049 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005050 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005051 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5052
5053 windowTop->setFocusable(true);
5054 windowSecond->setFocusable(true);
5055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5056 setFocusedWindow(windowTop);
5057 windowTop->consumeFocusEvent(true);
5058
5059 setFocusedWindow(windowSecond, windowTop);
5060 windowSecond->consumeFocusEvent(true);
5061 windowTop->consumeFocusEvent(false);
5062
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5064 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005065
5066 // Focused window should receive event.
5067 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5068}
5069
5070TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5071 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5072 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005073 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005074 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005075 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005076 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5077
5078 windowTop->setFocusable(true);
5079 windowSecond->setFocusable(true);
5080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5081 setFocusedWindow(windowSecond, windowTop);
5082
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005083 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5084 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005085
5086 // Event should be dropped.
5087 windowTop->assertNoEvents();
5088 windowSecond->assertNoEvents();
5089}
5090
5091TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5092 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5093 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005094 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005095 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005096 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5097 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005098 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5099
5100 window->setFocusable(true);
5101 previousFocusedWindow->setFocusable(true);
5102 window->setVisible(false);
5103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5104 setFocusedWindow(previousFocusedWindow);
5105 previousFocusedWindow->consumeFocusEvent(true);
5106
5107 // Requesting focus on invisible window takes focus from currently focused window.
5108 setFocusedWindow(window);
5109 previousFocusedWindow->consumeFocusEvent(false);
5110
5111 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005113 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5114 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005115
5116 // Window does not get focus event or key down.
5117 window->assertNoEvents();
5118
5119 // Window becomes visible.
5120 window->setVisible(true);
5121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5122
5123 // Window receives focus event.
5124 window->consumeFocusEvent(true);
5125 // Focused window receives key down.
5126 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5127}
5128
Vishnu Nair599f1412021-06-21 10:39:58 -07005129TEST_F(InputDispatcherTest, DisplayRemoved) {
5130 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5131 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005132 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005133 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5134
5135 // window is granted focus.
5136 window->setFocusable(true);
5137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5138 setFocusedWindow(window);
5139 window->consumeFocusEvent(true);
5140
5141 // When a display is removed window loses focus.
5142 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5143 window->consumeFocusEvent(false);
5144}
5145
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005146/**
5147 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5148 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5149 * of the 'slipperyEnterWindow'.
5150 *
5151 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5152 * a way so that the touched location is no longer covered by the top window.
5153 *
5154 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5155 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5156 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5157 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5158 * with ACTION_DOWN).
5159 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5160 * window moved itself away from the touched location and had Flag::SLIPPERY.
5161 *
5162 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5163 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5164 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5165 *
5166 * In this test, we ensure that the event received by the bottom window has
5167 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5168 */
5169TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005170 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5171 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005172
5173 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5174 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5175
5176 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005177 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005178 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005179 // Make sure this one overlaps the bottom window
5180 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5181 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5182 // one. Windows with the same owner are not considered to be occluding each other.
5183 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5184
5185 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005186 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005187 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5188
5189 mDispatcher->setInputWindows(
5190 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5191
5192 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5193 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5194 ADISPLAY_ID_DEFAULT, {{50, 50}});
5195 mDispatcher->notifyMotion(&args);
5196 slipperyExitWindow->consumeMotionDown();
5197 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5198 mDispatcher->setInputWindows(
5199 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5200
5201 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5202 ADISPLAY_ID_DEFAULT, {{51, 51}});
5203 mDispatcher->notifyMotion(&args);
5204
5205 slipperyExitWindow->consumeMotionCancel();
5206
5207 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5208 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5209}
5210
Garfield Tan1c7bc862020-01-28 13:24:04 -08005211class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5212protected:
5213 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5214 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5215
Chris Yea209fde2020-07-22 13:54:51 -07005216 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005217 sp<FakeWindowHandle> mWindow;
5218
5219 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005220 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005221 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005222 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005223 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5224 ASSERT_EQ(OK, mDispatcher->start());
5225
5226 setUpWindow();
5227 }
5228
5229 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005230 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005231 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005232
Vishnu Nair47074b82020-08-14 11:54:47 -07005233 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005235 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005236 mWindow->consumeFocusEvent(true);
5237 }
5238
Chris Ye2ad95392020-09-01 13:44:44 -07005239 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005240 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005241 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005242 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5243 mDispatcher->notifyKey(&keyArgs);
5244
5245 // Window should receive key down event.
5246 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5247 }
5248
5249 void expectKeyRepeatOnce(int32_t repeatCount) {
5250 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5251 InputEvent* repeatEvent = mWindow->consume();
5252 ASSERT_NE(nullptr, repeatEvent);
5253
5254 uint32_t eventType = repeatEvent->getType();
5255 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5256
5257 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5258 uint32_t eventAction = repeatKeyEvent->getAction();
5259 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5260 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5261 }
5262
Chris Ye2ad95392020-09-01 13:44:44 -07005263 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005264 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005265 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005266 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5267 mDispatcher->notifyKey(&keyArgs);
5268
5269 // Window should receive key down event.
5270 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005271 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005272 }
5273};
5274
5275TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005276 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005277 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5278 expectKeyRepeatOnce(repeatCount);
5279 }
5280}
5281
5282TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005283 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005284 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5285 expectKeyRepeatOnce(repeatCount);
5286 }
Harry Cutts33476232023-01-30 19:57:29 +00005287 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005288 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005289 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5290 expectKeyRepeatOnce(repeatCount);
5291 }
5292}
5293
5294TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005295 sendAndConsumeKeyDown(/*deviceId=*/1);
5296 expectKeyRepeatOnce(/*repeatCount=*/1);
5297 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005298 mWindow->assertNoEvents();
5299}
5300
5301TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005302 sendAndConsumeKeyDown(/*deviceId=*/1);
5303 expectKeyRepeatOnce(/*repeatCount=*/1);
5304 sendAndConsumeKeyDown(/*deviceId=*/2);
5305 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005306 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005307 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005308 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005309 expectKeyRepeatOnce(/*repeatCount=*/2);
5310 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005311 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005312 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005313 mWindow->assertNoEvents();
5314}
5315
5316TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005317 sendAndConsumeKeyDown(/*deviceId=*/1);
5318 expectKeyRepeatOnce(/*repeatCount=*/1);
5319 sendAndConsumeKeyDown(/*deviceId=*/2);
5320 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005321 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005322 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005323 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005324 mWindow->assertNoEvents();
5325}
5326
liushenxiang42232912021-05-21 20:24:09 +08005327TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5328 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005329 expectKeyRepeatOnce(/*repeatCount=*/1);
5330 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005331 mDispatcher->notifyDeviceReset(&args);
5332 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5333 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5334 mWindow->assertNoEvents();
5335}
5336
Garfield Tan1c7bc862020-01-28 13:24:04 -08005337TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Harry Cutts33476232023-01-30 19:57:29 +00005338 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005339 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5340 InputEvent* repeatEvent = mWindow->consume();
5341 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5342 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5343 IdGenerator::getSource(repeatEvent->getId()));
5344 }
5345}
5346
5347TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Harry Cutts33476232023-01-30 19:57:29 +00005348 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005349
5350 std::unordered_set<int32_t> idSet;
5351 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5352 InputEvent* repeatEvent = mWindow->consume();
5353 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5354 int32_t id = repeatEvent->getId();
5355 EXPECT_EQ(idSet.end(), idSet.find(id));
5356 idSet.insert(id);
5357 }
5358}
5359
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005360/* Test InputDispatcher for MultiDisplay */
5361class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5362public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005363 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005364 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005365
Chris Yea209fde2020-07-22 13:54:51 -07005366 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005367 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005368 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005369
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005370 // Set focus window for primary display, but focused display would be second one.
5371 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005372 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005374 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005375 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005376
Chris Yea209fde2020-07-22 13:54:51 -07005377 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005378 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005379 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005380 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005381 // Set focus display to second one.
5382 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5383 // Set focus window for second display.
5384 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005385 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005386 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005387 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005388 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005389 }
5390
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005391 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005392 InputDispatcherTest::TearDown();
5393
Chris Yea209fde2020-07-22 13:54:51 -07005394 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005395 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005396 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005397 windowInSecondary.clear();
5398 }
5399
5400protected:
Chris Yea209fde2020-07-22 13:54:51 -07005401 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005402 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005403 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005404 sp<FakeWindowHandle> windowInSecondary;
5405};
5406
5407TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5408 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5410 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005412 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005413 windowInSecondary->assertNoEvents();
5414
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005415 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5417 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5418 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005419 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005420 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005421}
5422
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005423TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005424 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5426 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005427 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005428 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005429 windowInSecondary->assertNoEvents();
5430
5431 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005433 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005434 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005435 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005436
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005437 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005438 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005440 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005441 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5442 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005443
5444 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005445 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005446 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005447 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005448 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005449 windowInSecondary->assertNoEvents();
5450}
5451
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005452// Test per-display input monitors for motion event.
5453TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005454 FakeMonitorReceiver monitorInPrimary =
5455 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5456 FakeMonitorReceiver monitorInSecondary =
5457 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005458
5459 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5461 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005463 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005464 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005465 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005466 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005467
5468 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5470 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5471 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005472 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005473 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005474 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005475 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005476
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08005477 // Lift up the touch from the second display
5478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5479 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5480 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5481 windowInSecondary->consumeMotionUp(SECOND_DISPLAY_ID);
5482 monitorInSecondary.consumeMotionUp(SECOND_DISPLAY_ID);
5483
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005484 // Test inject a non-pointer motion event.
5485 // If specific a display, it will dispatch to the focused window of particular display,
5486 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005490 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005491 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005492 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005493 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005494}
5495
5496// Test per-display input monitors for key event.
5497TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005498 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005499 FakeMonitorReceiver monitorInPrimary =
5500 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5501 FakeMonitorReceiver monitorInSecondary =
5502 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005503
5504 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5506 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005507 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005508 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005509 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005510 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005511}
5512
Vishnu Nair958da932020-08-21 17:12:37 -07005513TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5514 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005515 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005516 secondWindowInPrimary->setFocusable(true);
5517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5518 setFocusedWindow(secondWindowInPrimary);
5519 windowInPrimary->consumeFocusEvent(false);
5520 secondWindowInPrimary->consumeFocusEvent(true);
5521
5522 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5524 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005525 windowInPrimary->assertNoEvents();
5526 windowInSecondary->assertNoEvents();
5527 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5528}
5529
Arthur Hungdfd528e2021-12-08 13:23:04 +00005530TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5531 FakeMonitorReceiver monitorInPrimary =
5532 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5533 FakeMonitorReceiver monitorInSecondary =
5534 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5535
5536 // Test touch down on primary display.
5537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5538 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5540 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5541 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5542
5543 // Test touch down on second display.
5544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5545 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5547 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5548 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5549
5550 // Trigger cancel touch.
5551 mDispatcher->cancelCurrentTouch();
5552 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5553 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5554 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5555 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5556
5557 // Test inject a move motion event, no window/monitor should receive the event.
5558 ASSERT_EQ(InputEventInjectionResult::FAILED,
5559 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5560 ADISPLAY_ID_DEFAULT, {110, 200}))
5561 << "Inject motion event should return InputEventInjectionResult::FAILED";
5562 windowInPrimary->assertNoEvents();
5563 monitorInPrimary.assertNoEvents();
5564
5565 ASSERT_EQ(InputEventInjectionResult::FAILED,
5566 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5567 SECOND_DISPLAY_ID, {110, 200}))
5568 << "Inject motion event should return InputEventInjectionResult::FAILED";
5569 windowInSecondary->assertNoEvents();
5570 monitorInSecondary.assertNoEvents();
5571}
5572
Jackal Guof9696682018-10-05 12:23:23 +08005573class InputFilterTest : public InputDispatcherTest {
5574protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005575 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5576 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005577 NotifyMotionArgs motionArgs;
5578
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005579 motionArgs =
5580 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005581 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005582 motionArgs =
5583 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005584 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005585 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005586 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005587 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5588 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005589 } else {
5590 mFakePolicy->assertFilterInputEventWasNotCalled();
5591 }
5592 }
5593
5594 void testNotifyKey(bool expectToBeFiltered) {
5595 NotifyKeyArgs keyArgs;
5596
5597 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5598 mDispatcher->notifyKey(&keyArgs);
5599 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5600 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005601 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005602
5603 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005604 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005605 } else {
5606 mFakePolicy->assertFilterInputEventWasNotCalled();
5607 }
5608 }
5609};
5610
5611// Test InputFilter for MotionEvent
5612TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5613 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5614 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5615 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5616
5617 // Enable InputFilter
5618 mDispatcher->setInputFilterEnabled(true);
5619 // Test touch on both primary and second display, and check if both events are filtered.
5620 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5621 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5622
5623 // Disable InputFilter
5624 mDispatcher->setInputFilterEnabled(false);
5625 // Test touch on both primary and second display, and check if both events aren't filtered.
5626 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5627 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5628}
5629
5630// Test InputFilter for KeyEvent
5631TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5632 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5633 testNotifyKey(/*expectToBeFiltered*/ false);
5634
5635 // Enable InputFilter
5636 mDispatcher->setInputFilterEnabled(true);
5637 // Send a key event, and check if it is filtered.
5638 testNotifyKey(/*expectToBeFiltered*/ true);
5639
5640 // Disable InputFilter
5641 mDispatcher->setInputFilterEnabled(false);
5642 // Send a key event, and check if it isn't filtered.
5643 testNotifyKey(/*expectToBeFiltered*/ false);
5644}
5645
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005646// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5647// logical display coordinate space.
5648TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5649 ui::Transform firstDisplayTransform;
5650 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5651 ui::Transform secondDisplayTransform;
5652 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5653
5654 std::vector<gui::DisplayInfo> displayInfos(2);
5655 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5656 displayInfos[0].transform = firstDisplayTransform;
5657 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5658 displayInfos[1].transform = secondDisplayTransform;
5659
5660 mDispatcher->onWindowInfosChanged({}, displayInfos);
5661
5662 // Enable InputFilter
5663 mDispatcher->setInputFilterEnabled(true);
5664
5665 // Ensure the correct transforms are used for the displays.
5666 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5667 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5668}
5669
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005670class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5671protected:
5672 virtual void SetUp() override {
5673 InputDispatcherTest::SetUp();
5674
5675 /**
5676 * We don't need to enable input filter to test the injected event policy, but we enabled it
5677 * here to make the tests more realistic, since this policy only matters when inputfilter is
5678 * on.
5679 */
5680 mDispatcher->setInputFilterEnabled(true);
5681
5682 std::shared_ptr<InputApplicationHandle> application =
5683 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005684 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5685 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005686
5687 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5688 mWindow->setFocusable(true);
5689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5690 setFocusedWindow(mWindow);
5691 mWindow->consumeFocusEvent(true);
5692 }
5693
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005694 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5695 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005696 KeyEvent event;
5697
5698 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5699 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5700 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005701 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005702 const int32_t additionalPolicyFlags =
5703 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005705 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005706 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5707 policyFlags | additionalPolicyFlags));
5708
5709 InputEvent* received = mWindow->consume();
5710 ASSERT_NE(nullptr, received);
5711 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005712 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5713 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5714 ASSERT_EQ(flags, keyEvent.getFlags());
5715 }
5716
5717 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5718 int32_t flags) {
5719 MotionEvent event;
5720 PointerProperties pointerProperties[1];
5721 PointerCoords pointerCoords[1];
5722 pointerProperties[0].clear();
5723 pointerProperties[0].id = 0;
5724 pointerCoords[0].clear();
5725 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5726 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5727
5728 ui::Transform identityTransform;
5729 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5730 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5731 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5732 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5733 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005734 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005735 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005736 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5737
5738 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005740 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005741 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5742 policyFlags | additionalPolicyFlags));
5743
5744 InputEvent* received = mWindow->consume();
5745 ASSERT_NE(nullptr, received);
5746 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5747 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5748 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5749 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005750 }
5751
5752private:
5753 sp<FakeWindowHandle> mWindow;
5754};
5755
5756TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005757 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5758 // filter. Without it, the event will no different from a regularly injected event, and the
5759 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005760 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5761 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005762}
5763
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005764TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005765 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005766 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005767 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5768}
5769
5770TEST_F(InputFilterInjectionPolicyTest,
5771 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5772 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005773 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005774 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005775}
5776
5777TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005778 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5779 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005780}
5781
chaviwfd6d3512019-03-25 13:23:49 -07005782class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005783 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005784 InputDispatcherTest::SetUp();
5785
Chris Yea209fde2020-07-22 13:54:51 -07005786 std::shared_ptr<FakeApplicationHandle> application =
5787 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005788 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005789 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005790 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005791
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005792 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005793 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005794 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005795
5796 // Set focused application.
5797 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005798 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005799
5800 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005802 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005803 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005804 }
5805
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005806 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005807 InputDispatcherTest::TearDown();
5808
5809 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005810 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005811 }
5812
5813protected:
5814 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005815 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005816 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005817};
5818
5819// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5820// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5821// the onPointerDownOutsideFocus callback.
5822TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5825 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005827 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005828
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005829 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005830 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5831}
5832
5833// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5834// DOWN on the window that doesn't have focus. Ensure no window received the
5835// onPointerDownOutsideFocus callback.
5836TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005840 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005841
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005842 ASSERT_TRUE(mDispatcher->waitForIdle());
5843 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005844}
5845
5846// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5847// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5848TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5850 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005851 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005852 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005853
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005854 ASSERT_TRUE(mDispatcher->waitForIdle());
5855 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005856}
5857
5858// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5859// DOWN on the window that already has focus. Ensure no window received the
5860// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005861TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005863 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005864 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005866 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005867
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005868 ASSERT_TRUE(mDispatcher->waitForIdle());
5869 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005870}
5871
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005872// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5873// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5874TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5875 const MotionEvent event =
5876 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5877 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005878 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005879 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
5880 .build();
5881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
5882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5883 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
5884
5885 ASSERT_TRUE(mDispatcher->waitForIdle());
5886 mFakePolicy->assertOnPointerDownWasNotCalled();
5887 // Ensure that the unfocused window did not receive any FOCUS events.
5888 mUnfocusedWindow->assertNoEvents();
5889}
5890
chaviwaf87b3e2019-10-01 16:59:28 -07005891// These tests ensures we can send touch events to a single client when there are multiple input
5892// windows that point to the same client token.
5893class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
5894 virtual void SetUp() override {
5895 InputDispatcherTest::SetUp();
5896
Chris Yea209fde2020-07-22 13:54:51 -07005897 std::shared_ptr<FakeApplicationHandle> application =
5898 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005899 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
5900 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07005901 mWindow1->setFrame(Rect(0, 0, 100, 100));
5902
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005903 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
5904 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07005905 mWindow2->setFrame(Rect(100, 100, 200, 200));
5906
Arthur Hung72d8dc32020-03-28 00:48:39 +00005907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07005908 }
5909
5910protected:
5911 sp<FakeWindowHandle> mWindow1;
5912 sp<FakeWindowHandle> mWindow2;
5913
5914 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05005915 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07005916 vec2 vals = windowInfo->transform.transform(point.x, point.y);
5917 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07005918 }
5919
5920 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
5921 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005922 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07005923 InputEvent* event = window->consume();
5924
5925 ASSERT_NE(nullptr, event) << name.c_str()
5926 << ": consumer should have returned non-NULL event.";
5927
5928 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
5929 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
5930 << " event, got " << inputEventTypeToString(event->getType()) << " event";
5931
5932 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005933 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08005934 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07005935
5936 for (size_t i = 0; i < points.size(); i++) {
5937 float expectedX = points[i].x;
5938 float expectedY = points[i].y;
5939
5940 EXPECT_EQ(expectedX, motionEvent.getX(i))
5941 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
5942 << ", got " << motionEvent.getX(i);
5943 EXPECT_EQ(expectedY, motionEvent.getY(i))
5944 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
5945 << ", got " << motionEvent.getY(i);
5946 }
5947 }
chaviw9eaa22c2020-07-01 16:21:27 -07005948
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005949 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07005950 std::vector<PointF> expectedPoints) {
5951 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
5952 ADISPLAY_ID_DEFAULT, touchedPoints);
5953 mDispatcher->notifyMotion(&motionArgs);
5954
5955 // Always consume from window1 since it's the window that has the InputReceiver
5956 consumeMotionEvent(mWindow1, action, expectedPoints);
5957 }
chaviwaf87b3e2019-10-01 16:59:28 -07005958};
5959
5960TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
5961 // Touch Window 1
5962 PointF touchedPoint = {10, 10};
5963 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005964 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005965
5966 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005967 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005968
5969 // Touch Window 2
5970 touchedPoint = {150, 150};
5971 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005972 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005973}
5974
chaviw9eaa22c2020-07-01 16:21:27 -07005975TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
5976 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07005977 mWindow2->setWindowScale(0.5f, 0.5f);
5978
5979 // Touch Window 1
5980 PointF touchedPoint = {10, 10};
5981 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005982 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005983 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005984 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005985
5986 // Touch Window 2
5987 touchedPoint = {150, 150};
5988 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005989 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
5990 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005991
chaviw9eaa22c2020-07-01 16:21:27 -07005992 // Update the transform so rotation is set
5993 mWindow2->setWindowTransform(0, -1, 1, 0);
5994 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
5995 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005996}
5997
chaviw9eaa22c2020-07-01 16:21:27 -07005998TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005999 mWindow2->setWindowScale(0.5f, 0.5f);
6000
6001 // Touch Window 1
6002 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6003 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006004 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006005
6006 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006007 touchedPoints.push_back(PointF{150, 150});
6008 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006009 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006010
chaviw9eaa22c2020-07-01 16:21:27 -07006011 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006012 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006013 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006014
chaviw9eaa22c2020-07-01 16:21:27 -07006015 // Update the transform so rotation is set for Window 2
6016 mWindow2->setWindowTransform(0, -1, 1, 0);
6017 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006018 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006019}
6020
chaviw9eaa22c2020-07-01 16:21:27 -07006021TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006022 mWindow2->setWindowScale(0.5f, 0.5f);
6023
6024 // Touch Window 1
6025 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6026 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006027 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006028
6029 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006030 touchedPoints.push_back(PointF{150, 150});
6031 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006032
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006033 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006034
6035 // Move both windows
6036 touchedPoints = {{20, 20}, {175, 175}};
6037 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6038 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6039
chaviw9eaa22c2020-07-01 16:21:27 -07006040 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006041
chaviw9eaa22c2020-07-01 16:21:27 -07006042 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006043 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006044 expectedPoints.pop_back();
6045
6046 // Touch Window 2
6047 mWindow2->setWindowTransform(0, -1, 1, 0);
6048 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006049 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006050
6051 // Move both windows
6052 touchedPoints = {{20, 20}, {175, 175}};
6053 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6054 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6055
6056 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006057}
6058
6059TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6060 mWindow1->setWindowScale(0.5f, 0.5f);
6061
6062 // Touch Window 1
6063 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6064 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006065 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006066
6067 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006068 touchedPoints.push_back(PointF{150, 150});
6069 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006070
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006071 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006072
6073 // Move both windows
6074 touchedPoints = {{20, 20}, {175, 175}};
6075 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6076 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6077
chaviw9eaa22c2020-07-01 16:21:27 -07006078 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006079}
6080
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006081class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6082 virtual void SetUp() override {
6083 InputDispatcherTest::SetUp();
6084
Chris Yea209fde2020-07-22 13:54:51 -07006085 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006086 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006087 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6088 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006089 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006090 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006091 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006092
6093 // Set focused application.
6094 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6095
6096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006097 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006098 mWindow->consumeFocusEvent(true);
6099 }
6100
6101 virtual void TearDown() override {
6102 InputDispatcherTest::TearDown();
6103 mWindow.clear();
6104 }
6105
6106protected:
Chris Yea209fde2020-07-22 13:54:51 -07006107 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006108 sp<FakeWindowHandle> mWindow;
6109 static constexpr PointF WINDOW_LOCATION = {20, 20};
6110
6111 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006113 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6114 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006116 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6117 WINDOW_LOCATION));
6118 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006119
6120 sp<FakeWindowHandle> addSpyWindow() {
6121 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006122 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006123 spy->setTrustedOverlay(true);
6124 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006125 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006126 spy->setDispatchingTimeout(30ms);
6127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6128 return spy;
6129 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006130};
6131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006132// Send a tap and respond, which should not cause an ANR.
6133TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6134 tapOnWindow();
6135 mWindow->consumeMotionDown();
6136 mWindow->consumeMotionUp();
6137 ASSERT_TRUE(mDispatcher->waitForIdle());
6138 mFakePolicy->assertNotifyAnrWasNotCalled();
6139}
6140
6141// Send a regular key and respond, which should not cause an ANR.
6142TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006144 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6145 ASSERT_TRUE(mDispatcher->waitForIdle());
6146 mFakePolicy->assertNotifyAnrWasNotCalled();
6147}
6148
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006149TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6150 mWindow->setFocusable(false);
6151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6152 mWindow->consumeFocusEvent(false);
6153
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006154 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006155 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6156 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6157 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006159 // Key will not go to window because we have no focused window.
6160 // The 'no focused window' ANR timer should start instead.
6161
6162 // Now, the focused application goes away.
6163 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6164 // The key should get dropped and there should be no ANR.
6165
6166 ASSERT_TRUE(mDispatcher->waitForIdle());
6167 mFakePolicy->assertNotifyAnrWasNotCalled();
6168}
6169
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006170// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006171// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6172// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006173TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006174 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006175 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6176 WINDOW_LOCATION));
6177
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006178 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6179 ASSERT_TRUE(sequenceNum);
6180 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006181 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006182
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006184 mWindow->consumeMotionEvent(
6185 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006186 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006187 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006188}
6189
6190// Send a key to the app and have the app not respond right away.
6191TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6192 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006194 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6195 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006196 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006197 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006198 ASSERT_TRUE(mDispatcher->waitForIdle());
6199}
6200
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006201// We have a focused application, but no focused window
6202TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006203 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6205 mWindow->consumeFocusEvent(false);
6206
6207 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6210 WINDOW_LOCATION));
6211 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6212 mDispatcher->waitForIdle();
6213 mFakePolicy->assertNotifyAnrWasNotCalled();
6214
6215 // Once a focused event arrives, we get an ANR for this application
6216 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6217 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006218 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006219 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6220 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006221 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006222 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006223 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006224 ASSERT_TRUE(mDispatcher->waitForIdle());
6225}
6226
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006227/**
6228 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6229 * there will not be an ANR.
6230 */
6231TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6232 mWindow->setFocusable(false);
6233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6234 mWindow->consumeFocusEvent(false);
6235
6236 KeyEvent event;
6237 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6238 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6239
6240 // Define a valid key down event that is stale (too old).
6241 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6242 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006243 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006244
6245 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6246
6247 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006248 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006249 InputEventInjectionSync::WAIT_FOR_RESULT,
6250 INJECT_EVENT_TIMEOUT, policyFlags);
6251 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6252 << "Injection should fail because the event is stale";
6253
6254 ASSERT_TRUE(mDispatcher->waitForIdle());
6255 mFakePolicy->assertNotifyAnrWasNotCalled();
6256 mWindow->assertNoEvents();
6257}
6258
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006259// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006260// Make sure that we don't notify policy twice about the same ANR.
6261TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006262 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006263 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6264 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265
6266 // Once a focused event arrives, we get an ANR for this application
6267 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6268 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006269 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006270 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6271 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006272 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006273 const std::chrono::duration appTimeout =
6274 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6275 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006276
Vishnu Naire4df8752022-09-08 09:17:55 -07006277 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006278 // ANR should not be raised again. It is up to policy to do that if it desires.
6279 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006280
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006281 // If we now get a focused window, the ANR should stop, but the policy handles that via
6282 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006283 ASSERT_TRUE(mDispatcher->waitForIdle());
6284}
6285
6286// We have a focused application, but no focused window
6287TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006288 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6290 mWindow->consumeFocusEvent(false);
6291
6292 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006293 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006294 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006295 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6296 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006297
Vishnu Naire4df8752022-09-08 09:17:55 -07006298 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6299 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006300
6301 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006302 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303 ASSERT_TRUE(mDispatcher->waitForIdle());
6304 mWindow->assertNoEvents();
6305}
6306
6307/**
6308 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6309 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6310 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6311 * the ANR mechanism should still work.
6312 *
6313 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6314 * DOWN event, while not responding on the second one.
6315 */
6316TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6317 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6318 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6319 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6320 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6321 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006322 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323
6324 // Now send ACTION_UP, with identical timestamp
6325 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6326 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6327 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6328 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006329 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006330
6331 // We have now sent down and up. Let's consume first event and then ANR on the second.
6332 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6333 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006334 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006335}
6336
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006337// A spy window can receive an ANR
6338TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6339 sp<FakeWindowHandle> spy = addSpyWindow();
6340
6341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6343 WINDOW_LOCATION));
6344 mWindow->consumeMotionDown();
6345
6346 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6347 ASSERT_TRUE(sequenceNum);
6348 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006349 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006350
6351 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006352 spy->consumeMotionEvent(
6353 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006354 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006355 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006356}
6357
6358// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006359// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006360TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6361 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006362
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6364 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006365 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006367
6368 // Stuck on the ACTION_UP
6369 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006370 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006371
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006372 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006373 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006374 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6375 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006376
6377 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6378 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006379 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006380 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006381 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006382}
6383
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006384// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006385// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006386TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6387 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006388
6389 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006390 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6391 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006392
6393 mWindow->consumeMotionDown();
6394 // Stuck on the ACTION_UP
6395 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006396 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006397
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006398 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006399 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006400 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6401 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006402
6403 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6404 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006405 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006406 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006407 spy->assertNoEvents();
6408}
6409
6410TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6411 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6412
6413 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6414
6415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6416 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6417 WINDOW_LOCATION));
6418
6419 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6420 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6421 ASSERT_TRUE(consumeSeq);
6422
Prabir Pradhanedd96402022-02-15 01:46:16 -08006423 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006424
6425 monitor.finishEvent(*consumeSeq);
6426 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6427
6428 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006429 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006430}
6431
6432// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6433// process events, you don't get an anr. When the window later becomes unresponsive again, you
6434// get an ANR again.
6435// 1. tap -> block on ACTION_UP -> receive ANR
6436// 2. consume all pending events (= queue becomes healthy again)
6437// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6438TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6439 tapOnWindow();
6440
6441 mWindow->consumeMotionDown();
6442 // Block on ACTION_UP
6443 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006444 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006445 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6446 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006447 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006448 mWindow->assertNoEvents();
6449
6450 tapOnWindow();
6451 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006452 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006453 mWindow->consumeMotionUp();
6454
6455 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006456 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006457 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006458 mWindow->assertNoEvents();
6459}
6460
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006461// If a connection remains unresponsive for a while, make sure policy is only notified once about
6462// it.
6463TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006465 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6466 WINDOW_LOCATION));
6467
6468 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006469 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006470 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006471 // 'notifyConnectionUnresponsive' should only be called once per connection
6472 mFakePolicy->assertNotifyAnrWasNotCalled();
6473 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006474 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006475 mWindow->consumeMotionEvent(
6476 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006477 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006478 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006479 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006480 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006481}
6482
6483/**
6484 * If a window is processing a motion event, and then a key event comes in, the key event should
6485 * not to to the focused window until the motion is processed.
6486 *
6487 * Warning!!!
6488 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6489 * and the injection timeout that we specify when injecting the key.
6490 * We must have the injection timeout (10ms) be smaller than
6491 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6492 *
6493 * If that value changes, this test should also change.
6494 */
6495TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6496 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6498
6499 tapOnWindow();
6500 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6501 ASSERT_TRUE(downSequenceNum);
6502 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6503 ASSERT_TRUE(upSequenceNum);
6504 // Don't finish the events yet, and send a key
6505 // Injection will "succeed" because we will eventually give up and send the key to the focused
6506 // window even if motions are still being processed. But because the injection timeout is short,
6507 // we will receive INJECTION_TIMED_OUT as the result.
6508
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006509 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006510 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006511 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6512 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006513 // Key will not be sent to the window, yet, because the window is still processing events
6514 // and the key remains pending, waiting for the touch events to be processed
6515 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6516 ASSERT_FALSE(keySequenceNum);
6517
6518 std::this_thread::sleep_for(500ms);
6519 // if we wait long enough though, dispatcher will give up, and still send the key
6520 // to the focused window, even though we have not yet finished the motion event
6521 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6522 mWindow->finishEvent(*downSequenceNum);
6523 mWindow->finishEvent(*upSequenceNum);
6524}
6525
6526/**
6527 * If a window is processing a motion event, and then a key event comes in, the key event should
6528 * not go to the focused window until the motion is processed.
6529 * If then a new motion comes in, then the pending key event should be going to the currently
6530 * focused window right away.
6531 */
6532TEST_F(InputDispatcherSingleWindowAnr,
6533 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6534 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6536
6537 tapOnWindow();
6538 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6539 ASSERT_TRUE(downSequenceNum);
6540 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6541 ASSERT_TRUE(upSequenceNum);
6542 // Don't finish the events yet, and send a key
6543 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006545 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6546 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006547 // At this point, key is still pending, and should not be sent to the application yet.
6548 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6549 ASSERT_FALSE(keySequenceNum);
6550
6551 // Now tap down again. It should cause the pending key to go to the focused window right away.
6552 tapOnWindow();
6553 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6554 // the other events yet. We can finish events in any order.
6555 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6556 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6557 mWindow->consumeMotionDown();
6558 mWindow->consumeMotionUp();
6559 mWindow->assertNoEvents();
6560}
6561
6562class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6563 virtual void SetUp() override {
6564 InputDispatcherTest::SetUp();
6565
Chris Yea209fde2020-07-22 13:54:51 -07006566 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006567 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006568 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6569 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006570 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006571 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006572 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006573
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006574 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6575 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006576 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006577 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006578
6579 // Set focused application.
6580 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006581 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006582
6583 // Expect one focus window exist in display.
6584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006585 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006586 mFocusedWindow->consumeFocusEvent(true);
6587 }
6588
6589 virtual void TearDown() override {
6590 InputDispatcherTest::TearDown();
6591
6592 mUnfocusedWindow.clear();
6593 mFocusedWindow.clear();
6594 }
6595
6596protected:
Chris Yea209fde2020-07-22 13:54:51 -07006597 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006598 sp<FakeWindowHandle> mUnfocusedWindow;
6599 sp<FakeWindowHandle> mFocusedWindow;
6600 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6601 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6602 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6603
6604 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6605
6606 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6607
6608private:
6609 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6612 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006614 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6615 location));
6616 }
6617};
6618
6619// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6620// should be ANR'd first.
6621TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006623 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6624 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006625 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006626 mFocusedWindow->consumeMotionDown();
6627 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006628 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006629 // We consumed all events, so no ANR
6630 ASSERT_TRUE(mDispatcher->waitForIdle());
6631 mFakePolicy->assertNotifyAnrWasNotCalled();
6632
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006634 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6635 FOCUSED_WINDOW_LOCATION));
6636 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6637 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006638
6639 const std::chrono::duration timeout =
6640 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006641 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006642 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6643 // sequence to make it consistent
6644 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006645 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006646 mFocusedWindow->consumeMotionDown();
6647 // This cancel is generated because the connection was unresponsive
6648 mFocusedWindow->consumeMotionCancel();
6649 mFocusedWindow->assertNoEvents();
6650 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006651 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006652 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6653 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006654 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006655}
6656
6657// If we have 2 windows with identical timeouts that are both unresponsive,
6658// it doesn't matter which order they should have ANR.
6659// But we should receive ANR for both.
6660TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6661 // Set the timeout for unfocused window to match the focused window
6662 mUnfocusedWindow->setDispatchingTimeout(10ms);
6663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6664
6665 tapOnFocusedWindow();
6666 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006667 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6668 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6669 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006670
6671 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006672 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6673 mFocusedWindow->getToken() == anrConnectionToken2);
6674 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6675 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006676
6677 ASSERT_TRUE(mDispatcher->waitForIdle());
6678 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006679
6680 mFocusedWindow->consumeMotionDown();
6681 mFocusedWindow->consumeMotionUp();
6682 mUnfocusedWindow->consumeMotionOutside();
6683
Prabir Pradhanedd96402022-02-15 01:46:16 -08006684 sp<IBinder> responsiveToken1, responsiveToken2;
6685 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6686 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006687
6688 // Both applications should be marked as responsive, in any order
6689 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6690 mFocusedWindow->getToken() == responsiveToken2);
6691 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6692 mUnfocusedWindow->getToken() == responsiveToken2);
6693 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006694}
6695
6696// If a window is already not responding, the second tap on the same window should be ignored.
6697// We should also log an error to account for the dropped event (not tested here).
6698// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6699TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6700 tapOnFocusedWindow();
6701 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006702 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006703 // Receive the events, but don't respond
6704 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6705 ASSERT_TRUE(downEventSequenceNum);
6706 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6707 ASSERT_TRUE(upEventSequenceNum);
6708 const std::chrono::duration timeout =
6709 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006710 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006711
6712 // Tap once again
6713 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006714 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006715 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6716 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006717 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006718 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6719 FOCUSED_WINDOW_LOCATION));
6720 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6721 // valid touch target
6722 mUnfocusedWindow->assertNoEvents();
6723
6724 // Consume the first tap
6725 mFocusedWindow->finishEvent(*downEventSequenceNum);
6726 mFocusedWindow->finishEvent(*upEventSequenceNum);
6727 ASSERT_TRUE(mDispatcher->waitForIdle());
6728 // The second tap did not go to the focused window
6729 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006730 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006731 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6732 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006733 mFakePolicy->assertNotifyAnrWasNotCalled();
6734}
6735
6736// If you tap outside of all windows, there will not be ANR
6737TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006738 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006739 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6740 LOCATION_OUTSIDE_ALL_WINDOWS));
6741 ASSERT_TRUE(mDispatcher->waitForIdle());
6742 mFakePolicy->assertNotifyAnrWasNotCalled();
6743}
6744
6745// Since the focused window is paused, tapping on it should not produce any events
6746TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6747 mFocusedWindow->setPaused(true);
6748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6749
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006750 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006751 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6752 FOCUSED_WINDOW_LOCATION));
6753
6754 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6755 ASSERT_TRUE(mDispatcher->waitForIdle());
6756 // Should not ANR because the window is paused, and touches shouldn't go to it
6757 mFakePolicy->assertNotifyAnrWasNotCalled();
6758
6759 mFocusedWindow->assertNoEvents();
6760 mUnfocusedWindow->assertNoEvents();
6761}
6762
6763/**
6764 * If a window is processing a motion event, and then a key event comes in, the key event should
6765 * not to to the focused window until the motion is processed.
6766 * If a different window becomes focused at this time, the key should go to that window instead.
6767 *
6768 * Warning!!!
6769 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6770 * and the injection timeout that we specify when injecting the key.
6771 * We must have the injection timeout (10ms) be smaller than
6772 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6773 *
6774 * If that value changes, this test should also change.
6775 */
6776TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6777 // Set a long ANR timeout to prevent it from triggering
6778 mFocusedWindow->setDispatchingTimeout(2s);
6779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6780
6781 tapOnUnfocusedWindow();
6782 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6783 ASSERT_TRUE(downSequenceNum);
6784 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6785 ASSERT_TRUE(upSequenceNum);
6786 // Don't finish the events yet, and send a key
6787 // Injection will succeed because we will eventually give up and send the key to the focused
6788 // window even if motions are still being processed.
6789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006790 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006791 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6792 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006794 // Key will not be sent to the window, yet, because the window is still processing events
6795 // and the key remains pending, waiting for the touch events to be processed
6796 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6797 ASSERT_FALSE(keySequenceNum);
6798
6799 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006800 mFocusedWindow->setFocusable(false);
6801 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006803 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006804
6805 // Focus events should precede the key events
6806 mUnfocusedWindow->consumeFocusEvent(true);
6807 mFocusedWindow->consumeFocusEvent(false);
6808
6809 // Finish the tap events, which should unblock dispatcher
6810 mUnfocusedWindow->finishEvent(*downSequenceNum);
6811 mUnfocusedWindow->finishEvent(*upSequenceNum);
6812
6813 // Now that all queues are cleared and no backlog in the connections, the key event
6814 // can finally go to the newly focused "mUnfocusedWindow".
6815 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6816 mFocusedWindow->assertNoEvents();
6817 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006818 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006819}
6820
6821// When the touch stream is split across 2 windows, and one of them does not respond,
6822// then ANR should be raised and the touch should be canceled for the unresponsive window.
6823// The other window should not be affected by that.
6824TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6825 // Touch Window 1
6826 NotifyMotionArgs motionArgs =
6827 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6828 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6829 mDispatcher->notifyMotion(&motionArgs);
6830 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006831 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006832
6833 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006834 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6835 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006836 mDispatcher->notifyMotion(&motionArgs);
6837
6838 const std::chrono::duration timeout =
6839 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006840 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006841
6842 mUnfocusedWindow->consumeMotionDown();
6843 mFocusedWindow->consumeMotionDown();
6844 // Focused window may or may not receive ACTION_MOVE
6845 // But it should definitely receive ACTION_CANCEL due to the ANR
6846 InputEvent* event;
6847 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6848 ASSERT_TRUE(moveOrCancelSequenceNum);
6849 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6850 ASSERT_NE(nullptr, event);
6851 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6852 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6853 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6854 mFocusedWindow->consumeMotionCancel();
6855 } else {
6856 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6857 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006858 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006859 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6860 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006861
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006862 mUnfocusedWindow->assertNoEvents();
6863 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006864 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006865}
6866
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006867/**
6868 * If we have no focused window, and a key comes in, we start the ANR timer.
6869 * The focused application should add a focused window before the timer runs out to prevent ANR.
6870 *
6871 * If the user touches another application during this time, the key should be dropped.
6872 * Next, if a new focused window comes in, without toggling the focused application,
6873 * then no ANR should occur.
6874 *
6875 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6876 * but in some cases the policy may not update the focused application.
6877 */
6878TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6879 std::shared_ptr<FakeApplicationHandle> focusedApplication =
6880 std::make_shared<FakeApplicationHandle>();
6881 focusedApplication->setDispatchingTimeout(60ms);
6882 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
6883 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
6884 mFocusedWindow->setFocusable(false);
6885
6886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6887 mFocusedWindow->consumeFocusEvent(false);
6888
6889 // Send a key. The ANR timer should start because there is no focused window.
6890 // 'focusedApplication' will get blamed if this timer completes.
6891 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006892 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006893 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6894 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6895 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006896 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006897
6898 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
6899 // then the injected touches won't cause the focused event to get dropped.
6900 // The dispatcher only checks for whether the queue should be pruned upon queueing.
6901 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
6902 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
6903 // For this test, it means that the key would get delivered to the window once it becomes
6904 // focused.
6905 std::this_thread::sleep_for(10ms);
6906
6907 // Touch unfocused window. This should force the pending key to get dropped.
6908 NotifyMotionArgs motionArgs =
6909 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6910 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
6911 mDispatcher->notifyMotion(&motionArgs);
6912
6913 // We do not consume the motion right away, because that would require dispatcher to first
6914 // process (== drop) the key event, and by that time, ANR will be raised.
6915 // Set the focused window first.
6916 mFocusedWindow->setFocusable(true);
6917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6918 setFocusedWindow(mFocusedWindow);
6919 mFocusedWindow->consumeFocusEvent(true);
6920 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
6921 // to another application. This could be a bug / behaviour in the policy.
6922
6923 mUnfocusedWindow->consumeMotionDown();
6924
6925 ASSERT_TRUE(mDispatcher->waitForIdle());
6926 // Should not ANR because we actually have a focused window. It was just added too slowly.
6927 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
6928}
6929
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006930// These tests ensure we cannot send touch events to a window that's positioned behind a window
6931// that has feature NO_INPUT_CHANNEL.
6932// Layout:
6933// Top (closest to user)
6934// mNoInputWindow (above all windows)
6935// mBottomWindow
6936// Bottom (furthest from user)
6937class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
6938 virtual void SetUp() override {
6939 InputDispatcherTest::SetUp();
6940
6941 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006942 mNoInputWindow =
6943 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6944 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00006945 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006946 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006947 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6948 // It's perfectly valid for this window to not have an associated input channel
6949
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006950 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
6951 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006952 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
6953
6954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6955 }
6956
6957protected:
6958 std::shared_ptr<FakeApplicationHandle> mApplication;
6959 sp<FakeWindowHandle> mNoInputWindow;
6960 sp<FakeWindowHandle> mBottomWindow;
6961};
6962
6963TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
6964 PointF touchedPoint = {10, 10};
6965
6966 NotifyMotionArgs motionArgs =
6967 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6968 ADISPLAY_ID_DEFAULT, {touchedPoint});
6969 mDispatcher->notifyMotion(&motionArgs);
6970
6971 mNoInputWindow->assertNoEvents();
6972 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
6973 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
6974 // and therefore should prevent mBottomWindow from receiving touches
6975 mBottomWindow->assertNoEvents();
6976}
6977
6978/**
6979 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
6980 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
6981 */
6982TEST_F(InputDispatcherMultiWindowOcclusionTests,
6983 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006984 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6985 "Window with input channel and NO_INPUT_CHANNEL",
6986 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006987
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006988 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006989 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6990 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6991
6992 PointF touchedPoint = {10, 10};
6993
6994 NotifyMotionArgs motionArgs =
6995 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6996 ADISPLAY_ID_DEFAULT, {touchedPoint});
6997 mDispatcher->notifyMotion(&motionArgs);
6998
6999 mNoInputWindow->assertNoEvents();
7000 mBottomWindow->assertNoEvents();
7001}
7002
Vishnu Nair958da932020-08-21 17:12:37 -07007003class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7004protected:
7005 std::shared_ptr<FakeApplicationHandle> mApp;
7006 sp<FakeWindowHandle> mWindow;
7007 sp<FakeWindowHandle> mMirror;
7008
7009 virtual void SetUp() override {
7010 InputDispatcherTest::SetUp();
7011 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007012 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7013 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7014 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007015 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7016 mWindow->setFocusable(true);
7017 mMirror->setFocusable(true);
7018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7019 }
7020};
7021
7022TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7023 // Request focus on a mirrored window
7024 setFocusedWindow(mMirror);
7025
7026 // window gets focused
7027 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7029 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007030 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7031}
7032
7033// A focused & mirrored window remains focused only if the window and its mirror are both
7034// focusable.
7035TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7036 setFocusedWindow(mMirror);
7037
7038 // window gets focused
7039 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7041 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007042 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7044 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007045 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7046
7047 mMirror->setFocusable(false);
7048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7049
7050 // window loses focus since one of the windows associated with the token in not focusable
7051 mWindow->consumeFocusEvent(false);
7052
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007053 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7054 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007055 mWindow->assertNoEvents();
7056}
7057
7058// A focused & mirrored window remains focused until the window and its mirror both become
7059// invisible.
7060TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7061 setFocusedWindow(mMirror);
7062
7063 // window gets focused
7064 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7066 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007067 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7069 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007070 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7071
7072 mMirror->setVisible(false);
7073 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7074
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7076 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007077 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7079 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007080 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7081
7082 mWindow->setVisible(false);
7083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7084
7085 // window loses focus only after all windows associated with the token become invisible.
7086 mWindow->consumeFocusEvent(false);
7087
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007088 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7089 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007090 mWindow->assertNoEvents();
7091}
7092
7093// A focused & mirrored window remains focused until both windows are removed.
7094TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7095 setFocusedWindow(mMirror);
7096
7097 // window gets focused
7098 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7100 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007101 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7103 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007104 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7105
7106 // single window is removed but the window token remains focused
7107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7108
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7110 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007111 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7113 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007114 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7115
7116 // Both windows are removed
7117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7118 mWindow->consumeFocusEvent(false);
7119
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007120 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7121 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007122 mWindow->assertNoEvents();
7123}
7124
7125// Focus request can be pending until one window becomes visible.
7126TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7127 // Request focus on an invisible mirror.
7128 mWindow->setVisible(false);
7129 mMirror->setVisible(false);
7130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7131 setFocusedWindow(mMirror);
7132
7133 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007135 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7136 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007137
7138 mMirror->setVisible(true);
7139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7140
7141 // window gets focused
7142 mWindow->consumeFocusEvent(true);
7143 // window gets the pending key event
7144 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7145}
Prabir Pradhan99987712020-11-10 18:43:05 -08007146
7147class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7148protected:
7149 std::shared_ptr<FakeApplicationHandle> mApp;
7150 sp<FakeWindowHandle> mWindow;
7151 sp<FakeWindowHandle> mSecondWindow;
7152
7153 void SetUp() override {
7154 InputDispatcherTest::SetUp();
7155 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007156 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007157 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007158 mSecondWindow =
7159 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007160 mSecondWindow->setFocusable(true);
7161
7162 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7164
7165 setFocusedWindow(mWindow);
7166 mWindow->consumeFocusEvent(true);
7167 }
7168
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007169 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7170 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007171 mDispatcher->notifyPointerCaptureChanged(&args);
7172 }
7173
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007174 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7175 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007176 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007177 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7178 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007179 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007180 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007181 }
7182};
7183
7184TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7185 // Ensure that capture cannot be obtained for unfocused windows.
7186 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7187 mFakePolicy->assertSetPointerCaptureNotCalled();
7188 mSecondWindow->assertNoEvents();
7189
7190 // Ensure that capture can be enabled from the focus window.
7191 requestAndVerifyPointerCapture(mWindow, true);
7192
7193 // Ensure that capture cannot be disabled from a window that does not have capture.
7194 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7195 mFakePolicy->assertSetPointerCaptureNotCalled();
7196
7197 // Ensure that capture can be disabled from the window with capture.
7198 requestAndVerifyPointerCapture(mWindow, false);
7199}
7200
7201TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007202 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007203
7204 setFocusedWindow(mSecondWindow);
7205
7206 // Ensure that the capture disabled event was sent first.
7207 mWindow->consumeCaptureEvent(false);
7208 mWindow->consumeFocusEvent(false);
7209 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007210 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007211
7212 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007213 notifyPointerCaptureChanged({});
7214 notifyPointerCaptureChanged(request);
7215 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007216 mWindow->assertNoEvents();
7217 mSecondWindow->assertNoEvents();
7218 mFakePolicy->assertSetPointerCaptureNotCalled();
7219}
7220
7221TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007222 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007223
7224 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007225 notifyPointerCaptureChanged({});
7226 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007227
7228 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007229 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007230 mWindow->consumeCaptureEvent(false);
7231 mWindow->assertNoEvents();
7232}
7233
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007234TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7235 requestAndVerifyPointerCapture(mWindow, true);
7236
7237 // The first window loses focus.
7238 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007239 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007240 mWindow->consumeCaptureEvent(false);
7241
7242 // Request Pointer Capture from the second window before the notification from InputReader
7243 // arrives.
7244 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007245 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007246
7247 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007248 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007249
7250 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007251 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007252
7253 mSecondWindow->consumeFocusEvent(true);
7254 mSecondWindow->consumeCaptureEvent(true);
7255}
7256
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007257TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7258 // App repeatedly enables and disables capture.
7259 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7260 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7261 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7262 mFakePolicy->assertSetPointerCaptureCalled(false);
7263 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7264 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7265
7266 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7267 // first request is now stale, this should do nothing.
7268 notifyPointerCaptureChanged(firstRequest);
7269 mWindow->assertNoEvents();
7270
7271 // InputReader notifies that the second request was enabled.
7272 notifyPointerCaptureChanged(secondRequest);
7273 mWindow->consumeCaptureEvent(true);
7274}
7275
Prabir Pradhan7092e262022-05-03 16:51:09 +00007276TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7277 requestAndVerifyPointerCapture(mWindow, true);
7278
7279 // App toggles pointer capture off and on.
7280 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7281 mFakePolicy->assertSetPointerCaptureCalled(false);
7282
7283 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7284 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7285
7286 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7287 // preceding "disable" request.
7288 notifyPointerCaptureChanged(enableRequest);
7289
7290 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7291 // any notifications.
7292 mWindow->assertNoEvents();
7293}
7294
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007295class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7296protected:
7297 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007298
7299 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7300 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7301
7302 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7303 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7304
7305 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7306 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7307 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7308 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7309 MAXIMUM_OBSCURING_OPACITY);
7310
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007311 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007312 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007313 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007314
7315 sp<FakeWindowHandle> mTouchWindow;
7316
7317 virtual void SetUp() override {
7318 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007319 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007320 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7321 }
7322
7323 virtual void TearDown() override {
7324 InputDispatcherTest::TearDown();
7325 mTouchWindow.clear();
7326 }
7327
chaviw3277faf2021-05-19 16:45:23 -05007328 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7329 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007330 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007331 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007332 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007333 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007334 return window;
7335 }
7336
7337 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7338 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7339 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007340 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007341 // Generate an arbitrary PID based on the UID
7342 window->setOwnerInfo(1777 + (uid % 10000), uid);
7343 return window;
7344 }
7345
7346 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7347 NotifyMotionArgs args =
7348 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7349 ADISPLAY_ID_DEFAULT, points);
7350 mDispatcher->notifyMotion(&args);
7351 }
7352};
7353
7354TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007355 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007356 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007358
7359 touch();
7360
7361 mTouchWindow->assertNoEvents();
7362}
7363
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007364TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007365 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7366 const sp<FakeWindowHandle>& w =
7367 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7369
7370 touch();
7371
7372 mTouchWindow->assertNoEvents();
7373}
7374
7375TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007376 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7377 const sp<FakeWindowHandle>& w =
7378 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7380
7381 touch();
7382
7383 w->assertNoEvents();
7384}
7385
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007386TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007387 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007389
7390 touch();
7391
7392 mTouchWindow->consumeAnyMotionDown();
7393}
7394
7395TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007396 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007397 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007398 w->setFrame(Rect(0, 0, 50, 50));
7399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007400
7401 touch({PointF{100, 100}});
7402
7403 mTouchWindow->consumeAnyMotionDown();
7404}
7405
7406TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007407 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007408 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7410
7411 touch();
7412
7413 mTouchWindow->consumeAnyMotionDown();
7414}
7415
7416TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7417 const sp<FakeWindowHandle>& w =
7418 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007420
7421 touch();
7422
7423 mTouchWindow->consumeAnyMotionDown();
7424}
7425
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007426TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7427 const sp<FakeWindowHandle>& w =
7428 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7430
7431 touch();
7432
7433 w->assertNoEvents();
7434}
7435
7436/**
7437 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7438 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7439 * window, the occluding window will still receive ACTION_OUTSIDE event.
7440 */
7441TEST_F(InputDispatcherUntrustedTouchesTest,
7442 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7443 const sp<FakeWindowHandle>& w =
7444 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007445 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7447
7448 touch();
7449
7450 w->consumeMotionOutside();
7451}
7452
7453TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7454 const sp<FakeWindowHandle>& w =
7455 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007456 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7458
7459 touch();
7460
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007461 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007462}
7463
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007464TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007465 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007466 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7467 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007468 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7469
7470 touch();
7471
7472 mTouchWindow->consumeAnyMotionDown();
7473}
7474
7475TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7476 const sp<FakeWindowHandle>& w =
7477 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7478 MAXIMUM_OBSCURING_OPACITY);
7479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007480
7481 touch();
7482
7483 mTouchWindow->consumeAnyMotionDown();
7484}
7485
7486TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007487 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007488 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7489 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7491
7492 touch();
7493
7494 mTouchWindow->assertNoEvents();
7495}
7496
7497TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7498 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7499 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007500 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7501 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007502 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007503 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7504 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7506
7507 touch();
7508
7509 mTouchWindow->assertNoEvents();
7510}
7511
7512TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7513 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7514 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007515 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7516 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007517 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007518 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7519 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7521
7522 touch();
7523
7524 mTouchWindow->consumeAnyMotionDown();
7525}
7526
7527TEST_F(InputDispatcherUntrustedTouchesTest,
7528 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7529 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007530 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7531 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007532 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007533 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7534 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7536
7537 touch();
7538
7539 mTouchWindow->consumeAnyMotionDown();
7540}
7541
7542TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7543 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007544 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7545 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007546 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007547 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7548 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007550
7551 touch();
7552
7553 mTouchWindow->assertNoEvents();
7554}
7555
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007556TEST_F(InputDispatcherUntrustedTouchesTest,
7557 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7558 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007559 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7560 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007561 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007562 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7563 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7565
7566 touch();
7567
7568 mTouchWindow->assertNoEvents();
7569}
7570
7571TEST_F(InputDispatcherUntrustedTouchesTest,
7572 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7573 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007574 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7575 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007576 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007577 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7578 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7580
7581 touch();
7582
7583 mTouchWindow->consumeAnyMotionDown();
7584}
7585
7586TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7587 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007588 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7589 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7591
7592 touch();
7593
7594 mTouchWindow->consumeAnyMotionDown();
7595}
7596
7597TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7598 const sp<FakeWindowHandle>& w =
7599 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7601
7602 touch();
7603
7604 mTouchWindow->consumeAnyMotionDown();
7605}
7606
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007607TEST_F(InputDispatcherUntrustedTouchesTest,
7608 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7609 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7610 const sp<FakeWindowHandle>& w =
7611 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7613
7614 touch();
7615
7616 mTouchWindow->assertNoEvents();
7617}
7618
7619TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7620 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7621 const sp<FakeWindowHandle>& w =
7622 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7624
7625 touch();
7626
7627 mTouchWindow->consumeAnyMotionDown();
7628}
7629
7630TEST_F(InputDispatcherUntrustedTouchesTest,
7631 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7632 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7633 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007634 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7635 OPACITY_ABOVE_THRESHOLD);
7636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7637
7638 touch();
7639
7640 mTouchWindow->consumeAnyMotionDown();
7641}
7642
7643TEST_F(InputDispatcherUntrustedTouchesTest,
7644 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7645 const sp<FakeWindowHandle>& w1 =
7646 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7647 OPACITY_BELOW_THRESHOLD);
7648 const sp<FakeWindowHandle>& w2 =
7649 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7650 OPACITY_BELOW_THRESHOLD);
7651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7652
7653 touch();
7654
7655 mTouchWindow->assertNoEvents();
7656}
7657
7658/**
7659 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7660 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7661 * (which alone would result in allowing touches) does not affect the blocking behavior.
7662 */
7663TEST_F(InputDispatcherUntrustedTouchesTest,
7664 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7665 const sp<FakeWindowHandle>& wB =
7666 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7667 OPACITY_BELOW_THRESHOLD);
7668 const sp<FakeWindowHandle>& wC =
7669 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7670 OPACITY_BELOW_THRESHOLD);
7671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7672
7673 touch();
7674
7675 mTouchWindow->assertNoEvents();
7676}
7677
7678/**
7679 * This test is testing that a window from a different UID but with same application token doesn't
7680 * block the touch. Apps can share the application token for close UI collaboration for example.
7681 */
7682TEST_F(InputDispatcherUntrustedTouchesTest,
7683 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7684 const sp<FakeWindowHandle>& w =
7685 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7686 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7688
7689 touch();
7690
7691 mTouchWindow->consumeAnyMotionDown();
7692}
7693
arthurhungb89ccb02020-12-30 16:19:01 +08007694class InputDispatcherDragTests : public InputDispatcherTest {
7695protected:
7696 std::shared_ptr<FakeApplicationHandle> mApp;
7697 sp<FakeWindowHandle> mWindow;
7698 sp<FakeWindowHandle> mSecondWindow;
7699 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007700 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007701 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7702 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007703
7704 void SetUp() override {
7705 InputDispatcherTest::SetUp();
7706 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007707 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007708 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007709
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007710 mSecondWindow =
7711 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007712 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007713
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007714 mSpyWindow =
7715 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007716 mSpyWindow->setSpy(true);
7717 mSpyWindow->setTrustedOverlay(true);
7718 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7719
arthurhungb89ccb02020-12-30 16:19:01 +08007720 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007722 }
7723
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007724 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7725 switch (fromSource) {
7726 case AINPUT_SOURCE_TOUCHSCREEN:
7727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7729 ADISPLAY_ID_DEFAULT, {50, 50}))
7730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7731 break;
7732 case AINPUT_SOURCE_STYLUS:
7733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7734 injectMotionEvent(
7735 mDispatcher,
7736 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7737 AINPUT_SOURCE_STYLUS)
7738 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7739 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7740 .x(50)
7741 .y(50))
7742 .build()));
7743 break;
7744 case AINPUT_SOURCE_MOUSE:
7745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7746 injectMotionEvent(
7747 mDispatcher,
7748 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7749 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7750 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7751 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7752 .x(50)
7753 .y(50))
7754 .build()));
7755 break;
7756 default:
7757 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7758 }
arthurhungb89ccb02020-12-30 16:19:01 +08007759
7760 // Window should receive motion event.
7761 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007762 // Spy window should also receive motion event
7763 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007764 }
7765
7766 // Start performing drag, we will create a drag window and transfer touch to it.
7767 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7768 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007769 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007770 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007771 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007772 }
arthurhungb89ccb02020-12-30 16:19:01 +08007773
7774 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007775 mDragWindow =
7776 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007777 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007778 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007779 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007780
7781 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007782 bool transferred =
7783 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007784 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007785 if (transferred) {
7786 mWindow->consumeMotionCancel();
7787 mDragWindow->consumeMotionDown();
7788 }
7789 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007790 }
7791};
7792
7793TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007794 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007795
7796 // Move on window.
7797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7798 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7799 ADISPLAY_ID_DEFAULT, {50, 50}))
7800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7801 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7802 mWindow->consumeDragEvent(false, 50, 50);
7803 mSecondWindow->assertNoEvents();
7804
7805 // Move to another window.
7806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7807 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7808 ADISPLAY_ID_DEFAULT, {150, 50}))
7809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7810 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7811 mWindow->consumeDragEvent(true, 150, 50);
7812 mSecondWindow->consumeDragEvent(false, 50, 50);
7813
7814 // Move back to original window.
7815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7816 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7817 ADISPLAY_ID_DEFAULT, {50, 50}))
7818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7819 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7820 mWindow->consumeDragEvent(false, 50, 50);
7821 mSecondWindow->consumeDragEvent(true, -50, 50);
7822
7823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7824 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7825 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7826 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7827 mWindow->assertNoEvents();
7828 mSecondWindow->assertNoEvents();
7829}
7830
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007831TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007832 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007833
7834 // No cancel event after drag start
7835 mSpyWindow->assertNoEvents();
7836
7837 const MotionEvent secondFingerDownEvent =
7838 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7839 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007840 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7841 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007842 .build();
7843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7844 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7845 InputEventInjectionSync::WAIT_FOR_RESULT))
7846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7847
7848 // Receives cancel for first pointer after next pointer down
7849 mSpyWindow->consumeMotionCancel();
7850 mSpyWindow->consumeMotionDown();
7851
7852 mSpyWindow->assertNoEvents();
7853}
7854
arthurhungf452d0b2021-01-06 00:19:52 +08007855TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007856 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007857
7858 // Move on window.
7859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7860 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7861 ADISPLAY_ID_DEFAULT, {50, 50}))
7862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7863 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7864 mWindow->consumeDragEvent(false, 50, 50);
7865 mSecondWindow->assertNoEvents();
7866
7867 // Move to another window.
7868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7870 ADISPLAY_ID_DEFAULT, {150, 50}))
7871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7872 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7873 mWindow->consumeDragEvent(true, 150, 50);
7874 mSecondWindow->consumeDragEvent(false, 50, 50);
7875
7876 // drop to another window.
7877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7878 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7879 {150, 50}))
7880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7881 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7882 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7883 mWindow->assertNoEvents();
7884 mSecondWindow->assertNoEvents();
7885}
7886
arthurhung6d4bed92021-03-17 11:59:33 +08007887TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007888 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08007889
7890 // Move on window and keep button pressed.
7891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7892 injectMotionEvent(mDispatcher,
7893 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7894 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7895 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7896 .x(50)
7897 .y(50))
7898 .build()))
7899 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7900 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7901 mWindow->consumeDragEvent(false, 50, 50);
7902 mSecondWindow->assertNoEvents();
7903
7904 // Move to another window and release button, expect to drop item.
7905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7906 injectMotionEvent(mDispatcher,
7907 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7908 .buttonState(0)
7909 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7910 .x(150)
7911 .y(50))
7912 .build()))
7913 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7914 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7915 mWindow->assertNoEvents();
7916 mSecondWindow->assertNoEvents();
7917 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7918
7919 // nothing to the window.
7920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7921 injectMotionEvent(mDispatcher,
7922 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
7923 .buttonState(0)
7924 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7925 .x(150)
7926 .y(50))
7927 .build()))
7928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7929 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7930 mWindow->assertNoEvents();
7931 mSecondWindow->assertNoEvents();
7932}
7933
Arthur Hung54745652022-04-20 07:17:41 +00007934TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007935 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08007936
7937 // Set second window invisible.
7938 mSecondWindow->setVisible(false);
7939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
7940
7941 // Move on window.
7942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7943 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7944 ADISPLAY_ID_DEFAULT, {50, 50}))
7945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7946 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7947 mWindow->consumeDragEvent(false, 50, 50);
7948 mSecondWindow->assertNoEvents();
7949
7950 // Move to another window.
7951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7952 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7953 ADISPLAY_ID_DEFAULT, {150, 50}))
7954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7955 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7956 mWindow->consumeDragEvent(true, 150, 50);
7957 mSecondWindow->assertNoEvents();
7958
7959 // drop to another window.
7960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7961 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7962 {150, 50}))
7963 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7964 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7965 mFakePolicy->assertDropTargetEquals(nullptr);
7966 mWindow->assertNoEvents();
7967 mSecondWindow->assertNoEvents();
7968}
7969
Arthur Hung54745652022-04-20 07:17:41 +00007970TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007971 // Ensure window could track pointerIds if it didn't support split touch.
7972 mWindow->setPreventSplitting(true);
7973
Arthur Hung54745652022-04-20 07:17:41 +00007974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7975 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7976 {50, 50}))
7977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7978 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7979
7980 const MotionEvent secondFingerDownEvent =
7981 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7982 .displayId(ADISPLAY_ID_DEFAULT)
7983 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007984 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7985 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007986 .build();
7987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7988 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7989 InputEventInjectionSync::WAIT_FOR_RESULT))
7990 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00007991 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00007992
7993 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007994 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007995}
7996
7997TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
7998 // First down on second window.
7999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8000 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8001 {150, 50}))
8002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8003
8004 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8005
8006 // Second down on first window.
8007 const MotionEvent secondFingerDownEvent =
8008 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8009 .displayId(ADISPLAY_ID_DEFAULT)
8010 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008011 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8012 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008013 .build();
8014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8015 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8016 InputEventInjectionSync::WAIT_FOR_RESULT))
8017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8018 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8019
8020 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008021 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008022
8023 // Move on window.
8024 const MotionEvent secondFingerMoveEvent =
8025 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8026 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008027 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8028 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008029 .build();
8030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8031 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8032 InputEventInjectionSync::WAIT_FOR_RESULT));
8033 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8034 mWindow->consumeDragEvent(false, 50, 50);
8035 mSecondWindow->consumeMotionMove();
8036
8037 // Release the drag pointer should perform drop.
8038 const MotionEvent secondFingerUpEvent =
8039 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8040 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008041 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8042 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008043 .build();
8044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8045 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8046 InputEventInjectionSync::WAIT_FOR_RESULT));
8047 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8048 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8049 mWindow->assertNoEvents();
8050 mSecondWindow->consumeMotionMove();
8051}
8052
Arthur Hung3915c1f2022-05-31 07:17:17 +00008053TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008054 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008055
8056 // Update window of second display.
8057 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008058 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008059 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8060
8061 // Let second display has a touch state.
8062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8063 injectMotionEvent(mDispatcher,
8064 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8065 AINPUT_SOURCE_TOUCHSCREEN)
8066 .displayId(SECOND_DISPLAY_ID)
8067 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8068 .x(100)
8069 .y(100))
8070 .build()));
8071 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008072 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008073 // Update window again.
8074 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8075
8076 // Move on window.
8077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8078 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8079 ADISPLAY_ID_DEFAULT, {50, 50}))
8080 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8081 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8082 mWindow->consumeDragEvent(false, 50, 50);
8083 mSecondWindow->assertNoEvents();
8084
8085 // Move to another window.
8086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8087 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8088 ADISPLAY_ID_DEFAULT, {150, 50}))
8089 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8090 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8091 mWindow->consumeDragEvent(true, 150, 50);
8092 mSecondWindow->consumeDragEvent(false, 50, 50);
8093
8094 // drop to another window.
8095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8096 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8097 {150, 50}))
8098 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8099 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8100 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8101 mWindow->assertNoEvents();
8102 mSecondWindow->assertNoEvents();
8103}
8104
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008105TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8106 startDrag(true, AINPUT_SOURCE_MOUSE);
8107 // Move on window.
8108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8109 injectMotionEvent(mDispatcher,
8110 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8111 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8112 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8113 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8114 .x(50)
8115 .y(50))
8116 .build()))
8117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8118 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8119 mWindow->consumeDragEvent(false, 50, 50);
8120 mSecondWindow->assertNoEvents();
8121
8122 // Move to another window.
8123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8124 injectMotionEvent(mDispatcher,
8125 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8126 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8127 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8128 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8129 .x(150)
8130 .y(50))
8131 .build()))
8132 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8133 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8134 mWindow->consumeDragEvent(true, 150, 50);
8135 mSecondWindow->consumeDragEvent(false, 50, 50);
8136
8137 // drop to another window.
8138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8139 injectMotionEvent(mDispatcher,
8140 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8141 .buttonState(0)
8142 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8143 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8144 .x(150)
8145 .y(50))
8146 .build()))
8147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8148 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8149 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8150 mWindow->assertNoEvents();
8151 mSecondWindow->assertNoEvents();
8152}
8153
Vishnu Nair062a8672021-09-03 16:07:44 -07008154class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8155
8156TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008158 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8159 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008160 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008161 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8162 window->setFocusable(true);
8163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8164 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008165 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008166
8167 // With the flag set, window should not get any input
8168 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8169 mDispatcher->notifyKey(&keyArgs);
8170 window->assertNoEvents();
8171
8172 NotifyMotionArgs motionArgs =
8173 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8174 ADISPLAY_ID_DEFAULT);
8175 mDispatcher->notifyMotion(&motionArgs);
8176 window->assertNoEvents();
8177
8178 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008179 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8181
8182 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8183 mDispatcher->notifyKey(&keyArgs);
8184 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8185
8186 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8187 ADISPLAY_ID_DEFAULT);
8188 mDispatcher->notifyMotion(&motionArgs);
8189 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8190 window->assertNoEvents();
8191}
8192
8193TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8194 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8195 std::make_shared<FakeApplicationHandle>();
8196 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008197 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8198 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008199 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8200 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008201 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008202 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008203 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8204 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008205 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008206 window->setOwnerInfo(222, 222);
8207 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8208 window->setFocusable(true);
8209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8210 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008211 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008212
8213 // With the flag set, window should not get any input
8214 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8215 mDispatcher->notifyKey(&keyArgs);
8216 window->assertNoEvents();
8217
8218 NotifyMotionArgs motionArgs =
8219 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8220 ADISPLAY_ID_DEFAULT);
8221 mDispatcher->notifyMotion(&motionArgs);
8222 window->assertNoEvents();
8223
8224 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008225 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8227
8228 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8229 mDispatcher->notifyKey(&keyArgs);
8230 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8231
8232 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8233 ADISPLAY_ID_DEFAULT);
8234 mDispatcher->notifyMotion(&motionArgs);
8235 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8236 window->assertNoEvents();
8237}
8238
8239TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8240 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8241 std::make_shared<FakeApplicationHandle>();
8242 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008243 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8244 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008245 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8246 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008247 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008249 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8250 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008251 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008252 window->setOwnerInfo(222, 222);
8253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8254 window->setFocusable(true);
8255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8256 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008257 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008258
8259 // With the flag set, window should not get any input
8260 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8261 mDispatcher->notifyKey(&keyArgs);
8262 window->assertNoEvents();
8263
8264 NotifyMotionArgs motionArgs =
8265 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8266 ADISPLAY_ID_DEFAULT);
8267 mDispatcher->notifyMotion(&motionArgs);
8268 window->assertNoEvents();
8269
8270 // When the window is no longer obscured because it went on top, it should get input
8271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8272
8273 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8274 mDispatcher->notifyKey(&keyArgs);
8275 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8276
8277 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8278 ADISPLAY_ID_DEFAULT);
8279 mDispatcher->notifyMotion(&motionArgs);
8280 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8281 window->assertNoEvents();
8282}
8283
Antonio Kantekf16f2832021-09-28 04:39:20 +00008284class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8285protected:
8286 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008287 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008288 sp<FakeWindowHandle> mWindow;
8289 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008290 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008291
8292 void SetUp() override {
8293 InputDispatcherTest::SetUp();
8294
8295 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008296 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008297 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008298 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008299 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008300 mSecondWindow =
8301 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008302 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008303 mThirdWindow =
8304 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8305 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8306 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008307
8308 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8310 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8311 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008312 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008313
Antonio Kantek15beb512022-06-13 22:35:41 +00008314 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008315 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008316 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008317 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8318 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008319 mThirdWindow->assertNoEvents();
8320 }
8321
8322 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8323 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008324 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008325 SECOND_DISPLAY_ID)) {
8326 mWindow->assertNoEvents();
8327 mSecondWindow->assertNoEvents();
8328 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008329 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008330 }
8331
Antonio Kantek15beb512022-06-13 22:35:41 +00008332 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8333 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008334 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8335 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008336 mWindow->consumeTouchModeEvent(inTouchMode);
8337 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008338 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008339 }
8340};
8341
Antonio Kantek26defcf2022-02-08 01:12:27 +00008342TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008343 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008344 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8345 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008346 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008347}
8348
Antonio Kantek26defcf2022-02-08 01:12:27 +00008349TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8350 const WindowInfo& windowInfo = *mWindow->getInfo();
8351 int32_t ownerPid = windowInfo.ownerPid;
8352 int32_t ownerUid = windowInfo.ownerUid;
8353 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8354 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008355 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008356 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008357 mWindow->assertNoEvents();
8358 mSecondWindow->assertNoEvents();
8359}
8360
8361TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8362 const WindowInfo& windowInfo = *mWindow->getInfo();
8363 int32_t ownerPid = windowInfo.ownerPid;
8364 int32_t ownerUid = windowInfo.ownerUid;
8365 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008366 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008367 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008368}
8369
Antonio Kantekf16f2832021-09-28 04:39:20 +00008370TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008371 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008372 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8373 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008374 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008375 mWindow->assertNoEvents();
8376 mSecondWindow->assertNoEvents();
8377}
8378
Antonio Kantek15beb512022-06-13 22:35:41 +00008379TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8380 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8381 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8382 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008383 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008384 mWindow->assertNoEvents();
8385 mSecondWindow->assertNoEvents();
8386 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8387}
8388
Antonio Kantek48710e42022-03-24 14:19:30 -07008389TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8390 // Interact with the window first.
8391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8392 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8393 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8394
8395 // Then remove focus.
8396 mWindow->setFocusable(false);
8397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8398
8399 // Assert that caller can switch touch mode by owning one of the last interacted window.
8400 const WindowInfo& windowInfo = *mWindow->getInfo();
8401 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8402 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008403 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008404}
8405
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008406class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8407public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008408 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008409 std::shared_ptr<FakeApplicationHandle> application =
8410 std::make_shared<FakeApplicationHandle>();
8411 std::string name = "Fake Spy ";
8412 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008413 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8414 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008415 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008416 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008417 return spy;
8418 }
8419
8420 sp<FakeWindowHandle> createForeground() {
8421 std::shared_ptr<FakeApplicationHandle> application =
8422 std::make_shared<FakeApplicationHandle>();
8423 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008424 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8425 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008426 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008427 return window;
8428 }
8429
8430private:
8431 int mSpyCount{0};
8432};
8433
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008434using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008435/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008436 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8437 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008438TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8439 ScopedSilentDeath _silentDeath;
8440
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008441 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008442 spy->setTrustedOverlay(false);
8443 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8444 ".* not a trusted overlay");
8445}
8446
8447/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008448 * Input injection into a display with a spy window but no foreground windows should succeed.
8449 */
8450TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008451 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8453
8454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8455 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8456 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8457 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8458}
8459
8460/**
8461 * Verify the order in which different input windows receive events. The touched foreground window
8462 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8463 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8464 * receive events before ones belows it.
8465 *
8466 * Here, we set up a scenario with four windows in the following Z order from the top:
8467 * spy1, spy2, window, spy3.
8468 * We then inject an event and verify that the foreground "window" receives it first, followed by
8469 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8470 * window.
8471 */
8472TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8473 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008474 auto spy1 = createSpy();
8475 auto spy2 = createSpy();
8476 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8478 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8479 const size_t numChannels = channels.size();
8480
Michael Wright8e9a8562022-02-09 13:44:29 +00008481 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008482 if (!epollFd.ok()) {
8483 FAIL() << "Failed to create epoll fd";
8484 }
8485
8486 for (size_t i = 0; i < numChannels; i++) {
8487 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8488 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8489 FAIL() << "Failed to add fd to epoll";
8490 }
8491 }
8492
8493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8495 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8496
8497 std::vector<size_t> eventOrder;
8498 std::vector<struct epoll_event> events(numChannels);
8499 for (;;) {
8500 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8501 (100ms).count());
8502 if (nFds < 0) {
8503 FAIL() << "Failed to call epoll_wait";
8504 }
8505 if (nFds == 0) {
8506 break; // epoll_wait timed out
8507 }
8508 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008509 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008510 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008511 channels[i]->consumeMotionDown();
8512 }
8513 }
8514
8515 // Verify the order in which the events were received.
8516 EXPECT_EQ(3u, eventOrder.size());
8517 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8518 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8519 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8520}
8521
8522/**
8523 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8524 */
8525TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8526 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008527 auto spy = createSpy();
8528 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8530
8531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8532 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8533 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8534 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8535 spy->assertNoEvents();
8536}
8537
8538/**
8539 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8540 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8541 * to the window.
8542 */
8543TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8544 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008545 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008546 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8548
8549 // Inject an event outside the spy window's touchable region.
8550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8551 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8553 window->consumeMotionDown();
8554 spy->assertNoEvents();
8555 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8556 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8557 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8558 window->consumeMotionUp();
8559 spy->assertNoEvents();
8560
8561 // Inject an event inside the spy window's touchable region.
8562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8564 {5, 10}))
8565 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8566 window->consumeMotionDown();
8567 spy->consumeMotionDown();
8568}
8569
8570/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008571 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008572 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008573 */
8574TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8575 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008576 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008577 auto spy = createSpy();
8578 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008579 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008580 spy->setFrame(Rect{0, 0, 20, 20});
8581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8582
8583 // Inject an event outside the spy window's frame and touchable region.
8584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008585 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8586 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008587 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8588 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008589 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008590}
8591
8592/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008593 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8594 * pointers that are down within its bounds.
8595 */
8596TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8597 auto windowLeft = createForeground();
8598 windowLeft->setFrame({0, 0, 100, 200});
8599 auto windowRight = createForeground();
8600 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008601 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008602 spy->setFrame({0, 0, 200, 200});
8603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8604
8605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8606 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8607 {50, 50}))
8608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8609 windowLeft->consumeMotionDown();
8610 spy->consumeMotionDown();
8611
8612 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008613 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008614 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008615 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8616 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008617 .build();
8618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8619 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8620 InputEventInjectionSync::WAIT_FOR_RESULT))
8621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8622 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008623 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008624}
8625
8626/**
8627 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8628 * the spy should receive the second pointer with ACTION_DOWN.
8629 */
8630TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8631 auto window = createForeground();
8632 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008633 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008634 spyRight->setFrame({100, 0, 200, 200});
8635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8636
8637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8638 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8639 {50, 50}))
8640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8641 window->consumeMotionDown();
8642 spyRight->assertNoEvents();
8643
8644 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008645 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008646 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008647 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8648 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008649 .build();
8650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8651 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8652 InputEventInjectionSync::WAIT_FOR_RESULT))
8653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008654 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008655 spyRight->consumeMotionDown();
8656}
8657
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008658/**
8659 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8660 * windows should be allowed to control split touch.
8661 */
8662TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008663 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008664 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008665 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008666 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008667
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008668 auto window = createForeground();
8669 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008670
8671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8672
8673 // First finger down, no window touched.
8674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8675 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8676 {100, 200}))
8677 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8678 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8679 window->assertNoEvents();
8680
8681 // Second finger down on window, the window should receive touch down.
8682 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008683 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008684 .displayId(ADISPLAY_ID_DEFAULT)
8685 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008686 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8687 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008688 .build();
8689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8690 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8691 InputEventInjectionSync::WAIT_FOR_RESULT))
8692 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8693
8694 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008695 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008696}
8697
8698/**
8699 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8700 * do not receive key events.
8701 */
8702TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008703 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008704 spy->setFocusable(false);
8705
8706 auto window = createForeground();
8707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8708 setFocusedWindow(window);
8709 window->consumeFocusEvent(true);
8710
8711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8712 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8713 window->consumeKeyDown(ADISPLAY_ID_NONE);
8714
8715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8716 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8717 window->consumeKeyUp(ADISPLAY_ID_NONE);
8718
8719 spy->assertNoEvents();
8720}
8721
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008722using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8723
8724/**
8725 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8726 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8727 */
8728TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8729 auto window = createForeground();
8730 auto spy1 = createSpy();
8731 auto spy2 = createSpy();
8732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8733
8734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8736 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8737 window->consumeMotionDown();
8738 spy1->consumeMotionDown();
8739 spy2->consumeMotionDown();
8740
8741 // Pilfer pointers from the second spy window.
8742 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8743 spy2->assertNoEvents();
8744 spy1->consumeMotionCancel();
8745 window->consumeMotionCancel();
8746
8747 // The rest of the gesture should only be sent to the second spy window.
8748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8749 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8750 ADISPLAY_ID_DEFAULT))
8751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8752 spy2->consumeMotionMove();
8753 spy1->assertNoEvents();
8754 window->assertNoEvents();
8755}
8756
8757/**
8758 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8759 * in the middle of the gesture.
8760 */
8761TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8762 auto window = createForeground();
8763 auto spy = createSpy();
8764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8765
8766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8767 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8769 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8770 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8771
8772 window->releaseChannel();
8773
8774 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8775
8776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8777 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8778 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8779 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8780}
8781
8782/**
8783 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8784 * the spy, but not to any other windows.
8785 */
8786TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8787 auto spy = createSpy();
8788 auto window = createForeground();
8789
8790 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8791
8792 // First finger down on the window and the spy.
8793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8795 {100, 200}))
8796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8797 spy->consumeMotionDown();
8798 window->consumeMotionDown();
8799
8800 // Spy window pilfers the pointers.
8801 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8802 window->consumeMotionCancel();
8803
8804 // Second finger down on the window and spy, but the window should not receive the pointer down.
8805 const MotionEvent secondFingerDownEvent =
8806 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8807 .displayId(ADISPLAY_ID_DEFAULT)
8808 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008809 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8810 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008811 .build();
8812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8813 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8814 InputEventInjectionSync::WAIT_FOR_RESULT))
8815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8816
Harry Cutts33476232023-01-30 19:57:29 +00008817 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008818
8819 // Third finger goes down outside all windows, so injection should fail.
8820 const MotionEvent thirdFingerDownEvent =
8821 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8822 .displayId(ADISPLAY_ID_DEFAULT)
8823 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008824 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8825 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8826 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008827 .build();
8828 ASSERT_EQ(InputEventInjectionResult::FAILED,
8829 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8830 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008831 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008832
8833 spy->assertNoEvents();
8834 window->assertNoEvents();
8835}
8836
8837/**
8838 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8839 */
8840TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8841 auto spy = createSpy();
8842 spy->setFrame(Rect(0, 0, 100, 100));
8843 auto window = createForeground();
8844 window->setFrame(Rect(0, 0, 200, 200));
8845
8846 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8847
8848 // First finger down on the window only
8849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8851 {150, 150}))
8852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8853 window->consumeMotionDown();
8854
8855 // Second finger down on the spy and window
8856 const MotionEvent secondFingerDownEvent =
8857 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8858 .displayId(ADISPLAY_ID_DEFAULT)
8859 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008860 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8861 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008862 .build();
8863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8864 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8865 InputEventInjectionSync::WAIT_FOR_RESULT))
8866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8867 spy->consumeMotionDown();
8868 window->consumeMotionPointerDown(1);
8869
8870 // Third finger down on the spy and window
8871 const MotionEvent thirdFingerDownEvent =
8872 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8873 .displayId(ADISPLAY_ID_DEFAULT)
8874 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008875 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8876 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8877 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008878 .build();
8879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8880 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8881 InputEventInjectionSync::WAIT_FOR_RESULT))
8882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8883 spy->consumeMotionPointerDown(1);
8884 window->consumeMotionPointerDown(2);
8885
8886 // Spy window pilfers the pointers.
8887 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8888 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8889 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8890
8891 spy->assertNoEvents();
8892 window->assertNoEvents();
8893}
8894
8895/**
8896 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
8897 * other windows should be canceled. If this results in the cancellation of all pointers for some
8898 * window, then that window should receive ACTION_CANCEL.
8899 */
8900TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
8901 auto spy = createSpy();
8902 spy->setFrame(Rect(0, 0, 100, 100));
8903 auto window = createForeground();
8904 window->setFrame(Rect(0, 0, 200, 200));
8905
8906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8907
8908 // First finger down on both spy and window
8909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8910 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8911 {10, 10}))
8912 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8913 window->consumeMotionDown();
8914 spy->consumeMotionDown();
8915
8916 // Second finger down on the spy and window
8917 const MotionEvent secondFingerDownEvent =
8918 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8919 .displayId(ADISPLAY_ID_DEFAULT)
8920 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008921 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8922 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008923 .build();
8924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8925 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8926 InputEventInjectionSync::WAIT_FOR_RESULT))
8927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8928 spy->consumeMotionPointerDown(1);
8929 window->consumeMotionPointerDown(1);
8930
8931 // Spy window pilfers the pointers.
8932 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8933 window->consumeMotionCancel();
8934
8935 spy->assertNoEvents();
8936 window->assertNoEvents();
8937}
8938
8939/**
8940 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
8941 * be sent to other windows
8942 */
8943TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
8944 auto spy = createSpy();
8945 spy->setFrame(Rect(0, 0, 100, 100));
8946 auto window = createForeground();
8947 window->setFrame(Rect(0, 0, 200, 200));
8948
8949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8950
8951 // First finger down on both window and spy
8952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8954 {10, 10}))
8955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8956 window->consumeMotionDown();
8957 spy->consumeMotionDown();
8958
8959 // Spy window pilfers the pointers.
8960 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8961 window->consumeMotionCancel();
8962
8963 // Second finger down on the window only
8964 const MotionEvent secondFingerDownEvent =
8965 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8966 .displayId(ADISPLAY_ID_DEFAULT)
8967 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008968 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8969 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008970 .build();
8971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8972 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8973 InputEventInjectionSync::WAIT_FOR_RESULT))
8974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8975 window->consumeMotionDown();
8976 window->assertNoEvents();
8977
8978 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
8979 spy->consumeMotionMove();
8980 spy->assertNoEvents();
8981}
8982
Prabir Pradhand65552b2021-10-07 11:23:50 -07008983class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
8984public:
8985 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
8986 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8987 std::make_shared<FakeApplicationHandle>();
8988 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008989 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
8990 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008991 overlay->setFocusable(false);
8992 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008993 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008994 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008995 overlay->setTrustedOverlay(true);
8996
8997 std::shared_ptr<FakeApplicationHandle> application =
8998 std::make_shared<FakeApplicationHandle>();
8999 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009000 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9001 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009002 window->setFocusable(true);
9003 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009004
9005 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9007 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009008 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009009 return {std::move(overlay), std::move(window)};
9010 }
9011
9012 void sendFingerEvent(int32_t action) {
9013 NotifyMotionArgs motionArgs =
9014 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9015 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9016 mDispatcher->notifyMotion(&motionArgs);
9017 }
9018
9019 void sendStylusEvent(int32_t action) {
9020 NotifyMotionArgs motionArgs =
9021 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9022 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9023 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9024 mDispatcher->notifyMotion(&motionArgs);
9025 }
9026};
9027
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009028using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9029
9030TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9031 ScopedSilentDeath _silentDeath;
9032
Prabir Pradhand65552b2021-10-07 11:23:50 -07009033 auto [overlay, window] = setupStylusOverlayScenario();
9034 overlay->setTrustedOverlay(false);
9035 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9036 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9037 ".* not a trusted overlay");
9038}
9039
9040TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9041 auto [overlay, window] = setupStylusOverlayScenario();
9042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9043
9044 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9045 overlay->consumeMotionDown();
9046 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9047 overlay->consumeMotionUp();
9048
9049 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9050 window->consumeMotionDown();
9051 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9052 window->consumeMotionUp();
9053
9054 overlay->assertNoEvents();
9055 window->assertNoEvents();
9056}
9057
9058TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9059 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009060 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9062
9063 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9064 overlay->consumeMotionDown();
9065 window->consumeMotionDown();
9066 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9067 overlay->consumeMotionUp();
9068 window->consumeMotionUp();
9069
9070 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9071 window->consumeMotionDown();
9072 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9073 window->consumeMotionUp();
9074
9075 overlay->assertNoEvents();
9076 window->assertNoEvents();
9077}
9078
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009079/**
9080 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9081 * The scenario is as follows:
9082 * - The stylus interceptor overlay is configured as a spy window.
9083 * - The stylus interceptor spy receives the start of a new stylus gesture.
9084 * - It pilfers pointers and then configures itself to no longer be a spy.
9085 * - The stylus interceptor continues to receive the rest of the gesture.
9086 */
9087TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9088 auto [overlay, window] = setupStylusOverlayScenario();
9089 overlay->setSpy(true);
9090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9091
9092 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9093 overlay->consumeMotionDown();
9094 window->consumeMotionDown();
9095
9096 // The interceptor pilfers the pointers.
9097 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9098 window->consumeMotionCancel();
9099
9100 // The interceptor configures itself so that it is no longer a spy.
9101 overlay->setSpy(false);
9102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9103
9104 // It continues to receive the rest of the stylus gesture.
9105 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9106 overlay->consumeMotionMove();
9107 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9108 overlay->consumeMotionUp();
9109
9110 window->assertNoEvents();
9111}
9112
Prabir Pradhan5735a322022-04-11 17:23:34 +00009113struct User {
9114 int32_t mPid;
9115 int32_t mUid;
9116 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9117 std::unique_ptr<InputDispatcher>& mDispatcher;
9118
9119 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9120 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9121
9122 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9123 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9124 ADISPLAY_ID_DEFAULT, {100, 200},
9125 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9126 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9127 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9128 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9129 }
9130
9131 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009132 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009133 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009134 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009135 mPolicyFlags);
9136 }
9137
9138 sp<FakeWindowHandle> createWindow() const {
9139 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9140 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009141 sp<FakeWindowHandle> window =
9142 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9143 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009144 window->setOwnerInfo(mPid, mUid);
9145 return window;
9146 }
9147};
9148
9149using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9150
9151TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9152 auto owner = User(mDispatcher, 10, 11);
9153 auto window = owner.createWindow();
9154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9155
9156 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9157 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9158 window->consumeMotionDown();
9159
9160 setFocusedWindow(window);
9161 window->consumeFocusEvent(true);
9162
9163 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9164 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9165 window->consumeKeyDown(ADISPLAY_ID_NONE);
9166}
9167
9168TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9169 auto owner = User(mDispatcher, 10, 11);
9170 auto window = owner.createWindow();
9171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9172
9173 auto rando = User(mDispatcher, 20, 21);
9174 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9175 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9176
9177 setFocusedWindow(window);
9178 window->consumeFocusEvent(true);
9179
9180 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9181 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9182 window->assertNoEvents();
9183}
9184
9185TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9186 auto owner = User(mDispatcher, 10, 11);
9187 auto window = owner.createWindow();
9188 auto spy = owner.createWindow();
9189 spy->setSpy(true);
9190 spy->setTrustedOverlay(true);
9191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9192
9193 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9194 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9195 spy->consumeMotionDown();
9196 window->consumeMotionDown();
9197}
9198
9199TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9200 auto owner = User(mDispatcher, 10, 11);
9201 auto window = owner.createWindow();
9202
9203 auto rando = User(mDispatcher, 20, 21);
9204 auto randosSpy = rando.createWindow();
9205 randosSpy->setSpy(true);
9206 randosSpy->setTrustedOverlay(true);
9207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9208
9209 // The event is targeted at owner's window, so injection should succeed, but the spy should
9210 // not receive the event.
9211 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9212 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9213 randosSpy->assertNoEvents();
9214 window->consumeMotionDown();
9215}
9216
9217TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9218 auto owner = User(mDispatcher, 10, 11);
9219 auto window = owner.createWindow();
9220
9221 auto rando = User(mDispatcher, 20, 21);
9222 auto randosSpy = rando.createWindow();
9223 randosSpy->setSpy(true);
9224 randosSpy->setTrustedOverlay(true);
9225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9226
9227 // A user that has injection permission can inject into any window.
9228 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9229 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9230 ADISPLAY_ID_DEFAULT));
9231 randosSpy->consumeMotionDown();
9232 window->consumeMotionDown();
9233
9234 setFocusedWindow(randosSpy);
9235 randosSpy->consumeFocusEvent(true);
9236
9237 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9238 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9239 window->assertNoEvents();
9240}
9241
9242TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9243 auto owner = User(mDispatcher, 10, 11);
9244 auto window = owner.createWindow();
9245
9246 auto rando = User(mDispatcher, 20, 21);
9247 auto randosWindow = rando.createWindow();
9248 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9249 randosWindow->setWatchOutsideTouch(true);
9250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9251
9252 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9253 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9254 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9255 window->consumeMotionDown();
9256 randosWindow->consumeMotionOutside();
9257}
9258
Garfield Tane84e6f92019-08-29 17:28:41 -07009259} // namespace android::inputdispatcher