blob: cda677e54e6590dd72c82aaa01d282a440cdead5 [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,
2055 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2056 {100, 100}))
2057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2058 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2059 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002060}
2061
2062/**
2063 * Two windows: a window on the left and window on the right.
2064 * A third window, wallpaper, is behind both windows, and spans both top windows.
2065 * The first touch down goes to the left window. A second pointer touches down on the right window.
2066 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2067 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2068 * ACTION_POINTER_DOWN(1).
2069 */
2070TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2071 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2072 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002073 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002074 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002075 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002076
2077 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002078 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002079 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002080 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002081
2082 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002083 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002084 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002085 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002086
2087 mDispatcher->setInputWindows(
2088 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2089
2090 // Touch down on left window
2091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2092 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2093 {100, 100}))
2094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2095
2096 // Both foreground window and its wallpaper should receive the touch down
2097 leftWindow->consumeMotionDown();
2098 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2099
2100 // Second finger down on the right window
2101 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002102 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002103 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002104 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2105 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002106 .build();
2107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2108 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2109 InputEventInjectionSync::WAIT_FOR_RESULT))
2110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2111
2112 leftWindow->consumeMotionMove();
2113 // Since the touch is split, right window gets ACTION_DOWN
2114 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002115 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002116 expectedWallpaperFlags);
2117
2118 // Now, leftWindow, which received the first finger, disappears.
2119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2120 leftWindow->consumeMotionCancel();
2121 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2122 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2123
2124 // The pointer that's still down on the right window moves, and goes to the right window only.
2125 // As far as the dispatcher's concerned though, both pointers are still present.
2126 const MotionEvent secondFingerMoveEvent =
2127 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2128 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002129 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2130 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002131 .build();
2132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2133 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2134 InputEventInjectionSync::WAIT_FOR_RESULT));
2135 rightWindow->consumeMotionMove();
2136
2137 leftWindow->assertNoEvents();
2138 rightWindow->assertNoEvents();
2139 wallpaperWindow->assertNoEvents();
2140}
2141
Arthur Hungc539dbb2022-12-08 07:45:36 +00002142/**
2143 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2144 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2145 * The right window should receive ACTION_DOWN.
2146 */
2147TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002149 sp<FakeWindowHandle> leftWindow =
2150 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2151 leftWindow->setFrame(Rect(0, 0, 200, 200));
2152 leftWindow->setDupTouchToWallpaper(true);
2153 leftWindow->setSlippery(true);
2154
2155 sp<FakeWindowHandle> rightWindow =
2156 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2157 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002158
2159 sp<FakeWindowHandle> wallpaperWindow =
2160 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2161 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002162
Arthur Hungc539dbb2022-12-08 07:45:36 +00002163 mDispatcher->setInputWindows(
2164 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002165
Arthur Hungc539dbb2022-12-08 07:45:36 +00002166 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2168 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002169 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002170 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002171
2172 // Both foreground window and its wallpaper should receive the touch down
2173 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002174 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2175
Arthur Hungc539dbb2022-12-08 07:45:36 +00002176 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002178 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2179 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002180 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2181
Arthur Hungc539dbb2022-12-08 07:45:36 +00002182 leftWindow->consumeMotionCancel();
2183 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2184 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002185}
2186
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002187/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002188 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2189 * interactive, it might stop sending this flag.
2190 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2191 * to have a consistent input stream.
2192 *
2193 * Test procedure:
2194 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2195 * DOWN (new gesture).
2196 *
2197 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2198 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2199 *
2200 * We technically just need a single window here, but we are using two windows (spy on top and a
2201 * regular window below) to emulate the actual situation where it happens on the device.
2202 */
2203TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2204 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2205 sp<FakeWindowHandle> spyWindow =
2206 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2207 spyWindow->setFrame(Rect(0, 0, 200, 200));
2208 spyWindow->setTrustedOverlay(true);
2209 spyWindow->setSpy(true);
2210
2211 sp<FakeWindowHandle> window =
2212 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2213 window->setFrame(Rect(0, 0, 200, 200));
2214
2215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2216 const int32_t touchDeviceId = 4;
2217 NotifyMotionArgs args;
2218
2219 // Two pointers down
2220 mDispatcher->notifyMotion(&(
2221 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2222 .deviceId(touchDeviceId)
2223 .policyFlags(DEFAULT_POLICY_FLAGS)
2224 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2225 .build()));
2226
2227 mDispatcher->notifyMotion(&(
2228 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2229 .deviceId(touchDeviceId)
2230 .policyFlags(DEFAULT_POLICY_FLAGS)
2231 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2232 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2233 .build()));
2234 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2235 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2236 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2237 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2238
2239 // Cancel the current gesture. Send the cancel without the default policy flags.
2240 mDispatcher->notifyMotion(&(
2241 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2242 .deviceId(touchDeviceId)
2243 .policyFlags(0)
2244 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2245 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2246 .build()));
2247 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2248 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2249
2250 // We don't need to reset the device to reproduce the issue, but the reset event typically
2251 // follows, so we keep it here to model the actual listener behaviour more closely.
2252 NotifyDeviceResetArgs resetArgs;
2253 resetArgs.id = 1; // arbitrary id
2254 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2255 resetArgs.deviceId = touchDeviceId;
2256 mDispatcher->notifyDeviceReset(&resetArgs);
2257
2258 // Start new gesture
2259 mDispatcher->notifyMotion(&(
2260 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2261 .deviceId(touchDeviceId)
2262 .policyFlags(DEFAULT_POLICY_FLAGS)
2263 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2264 .build()));
2265 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2266 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2267
2268 // No more events
2269 spyWindow->assertNoEvents();
2270 window->assertNoEvents();
2271}
2272
2273/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002274 * Two windows: a window on the left and a window on the right.
2275 * Mouse is hovered from the right window into the left window.
2276 * Next, we tap on the left window, where the cursor was last seen.
2277 * The second tap is done onto the right window.
2278 * The mouse and tap are from two different devices.
2279 * We technically don't need to set the downtime / eventtime for these events, but setting these
2280 * explicitly helps during debugging.
2281 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2282 * In the buggy implementation, a tap on the right window would cause a crash.
2283 */
2284TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2285 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2286 sp<FakeWindowHandle> leftWindow =
2287 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2288 leftWindow->setFrame(Rect(0, 0, 200, 200));
2289
2290 sp<FakeWindowHandle> rightWindow =
2291 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2292 rightWindow->setFrame(Rect(200, 0, 400, 200));
2293
2294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2295 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2296 // stale.
2297 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2298 const int32_t mouseDeviceId = 6;
2299 const int32_t touchDeviceId = 4;
2300 // Move the cursor from right
2301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2302 injectMotionEvent(mDispatcher,
2303 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2304 AINPUT_SOURCE_MOUSE)
2305 .deviceId(mouseDeviceId)
2306 .downTime(baseTime + 10)
2307 .eventTime(baseTime + 20)
2308 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2309 .x(300)
2310 .y(100))
2311 .build()));
2312 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2313
2314 // .. to the left window
2315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2316 injectMotionEvent(mDispatcher,
2317 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2318 AINPUT_SOURCE_MOUSE)
2319 .deviceId(mouseDeviceId)
2320 .downTime(baseTime + 10)
2321 .eventTime(baseTime + 30)
2322 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2323 .x(110)
2324 .y(100))
2325 .build()));
2326 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2327 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2328 // Now tap the left window
2329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2330 injectMotionEvent(mDispatcher,
2331 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2332 AINPUT_SOURCE_TOUCHSCREEN)
2333 .deviceId(touchDeviceId)
2334 .downTime(baseTime + 40)
2335 .eventTime(baseTime + 40)
2336 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2337 .x(100)
2338 .y(100))
2339 .build()));
2340 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2341 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2342
2343 // release tap
2344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2345 injectMotionEvent(mDispatcher,
2346 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2347 AINPUT_SOURCE_TOUCHSCREEN)
2348 .deviceId(touchDeviceId)
2349 .downTime(baseTime + 40)
2350 .eventTime(baseTime + 50)
2351 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2352 .x(100)
2353 .y(100))
2354 .build()));
2355 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2356
2357 // Tap the window on the right
2358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2359 injectMotionEvent(mDispatcher,
2360 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2361 AINPUT_SOURCE_TOUCHSCREEN)
2362 .deviceId(touchDeviceId)
2363 .downTime(baseTime + 60)
2364 .eventTime(baseTime + 60)
2365 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2366 .x(300)
2367 .y(100))
2368 .build()));
2369 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2370
2371 // release tap
2372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2373 injectMotionEvent(mDispatcher,
2374 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2375 AINPUT_SOURCE_TOUCHSCREEN)
2376 .deviceId(touchDeviceId)
2377 .downTime(baseTime + 60)
2378 .eventTime(baseTime + 70)
2379 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2380 .x(300)
2381 .y(100))
2382 .build()));
2383 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2384
2385 // No more events
2386 leftWindow->assertNoEvents();
2387 rightWindow->assertNoEvents();
2388}
2389
2390/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002391 * Two windows: a window on the left and a window on the right.
2392 * Mouse is clicked on the left window and remains down. Touch is touched on the right and remains
2393 * down. Then, on the left window, also place second touch pointer down.
2394 * This test tries to reproduce a crash.
2395 * In the buggy implementation, second pointer down on the left window would cause a crash.
2396 */
2397TEST_F(InputDispatcherTest, MultiDeviceSplitTouch) {
2398 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2399 sp<FakeWindowHandle> leftWindow =
2400 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2401 leftWindow->setFrame(Rect(0, 0, 200, 200));
2402
2403 sp<FakeWindowHandle> rightWindow =
2404 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2405 rightWindow->setFrame(Rect(200, 0, 400, 200));
2406
2407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2408
2409 const int32_t touchDeviceId = 4;
2410 const int32_t mouseDeviceId = 6;
2411 NotifyMotionArgs args;
2412
2413 // Start hovering over the left window
2414 mDispatcher->notifyMotion(&(
2415 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2416 .deviceId(mouseDeviceId)
2417 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2418 .build()));
2419 leftWindow->consumeMotionEvent(
2420 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2421
2422 // Mouse down on left window
2423 mDispatcher->notifyMotion(&(
2424 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2425 .deviceId(mouseDeviceId)
2426 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2427 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2428 .build()));
2429
2430 leftWindow->consumeMotionEvent(
2431 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
2432 leftWindow->consumeMotionEvent(
2433 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2434
2435 mDispatcher->notifyMotion(&(
2436 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2437 .deviceId(mouseDeviceId)
2438 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2439 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2440 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2441 .build()));
2442 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2443
2444 // First touch pointer down on right window
2445 mDispatcher->notifyMotion(&(
2446 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2447 .deviceId(touchDeviceId)
2448 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2449 .build()));
2450 leftWindow->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2451
2452 rightWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2453
2454 // Second touch pointer down on left window
2455 mDispatcher->notifyMotion(&(
2456 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2457 .deviceId(touchDeviceId)
2458 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2459 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2460 .build()));
2461 leftWindow->consumeMotionEvent(
2462 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2463 // This MOVE event is not necessary (doesn't carry any new information), but it's there in the
2464 // current implementation.
2465 const std::map<int32_t, PointF> expectedPointers{{0, PointF{100, 100}}};
2466 rightWindow->consumeMotionEvent(
2467 AllOf(WithMotionAction(ACTION_MOVE), WithPointers(expectedPointers)));
2468
2469 leftWindow->assertNoEvents();
2470 rightWindow->assertNoEvents();
2471}
2472
2473/**
2474 * On a single window, use two different devices: mouse and touch.
2475 * Touch happens first, with two pointers going down, and then the first pointer leaving.
2476 * Mouse is clicked next, which causes the touch stream to be aborted with ACTION_CANCEL.
2477 * Finally, a second touch pointer goes down again. Ensure the second touch pointer is ignored,
2478 * because the mouse is currently down, and a POINTER_DOWN event from the touchscreen does not
2479 * represent a new gesture.
2480 */
2481TEST_F(InputDispatcherTest, MixedTouchAndMouseWithPointerDown) {
2482 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2483 sp<FakeWindowHandle> window =
2484 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2485 window->setFrame(Rect(0, 0, 400, 400));
2486
2487 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2488
2489 const int32_t touchDeviceId = 4;
2490 const int32_t mouseDeviceId = 6;
2491 NotifyMotionArgs args;
2492
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08002493 // First touch pointer down
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002494 mDispatcher->notifyMotion(&(
2495 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2496 .deviceId(touchDeviceId)
2497 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2498 .build()));
2499 // Second touch pointer down
2500 mDispatcher->notifyMotion(&(
2501 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2502 .deviceId(touchDeviceId)
2503 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2504 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2505 .build()));
2506 // First touch pointer lifts. The second one remains down
2507 mDispatcher->notifyMotion(&(
2508 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2509 .deviceId(touchDeviceId)
2510 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2511 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2512 .build()));
2513 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2514 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2515 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
2516
2517 // Mouse down. The touch should be canceled
2518 mDispatcher->notifyMotion(&(
2519 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2520 .deviceId(mouseDeviceId)
2521 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2522 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2523 .build()));
2524
2525 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
2526 WithPointerCount(2u)));
2527 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2528
2529 mDispatcher->notifyMotion(&(
2530 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2531 .deviceId(mouseDeviceId)
2532 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2533 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2534 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2535 .build()));
2536 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2537
2538 // Second touch pointer down.
2539 mDispatcher->notifyMotion(&(
2540 args = MotionArgsBuilder(POINTER_0_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2541 .deviceId(touchDeviceId)
2542 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2543 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2544 .build()));
2545 // The pointer_down event should be ignored
2546 window->assertNoEvents();
2547}
2548
2549/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002550 * This test is similar to the test above, but the sequence of injected events is different.
2551 *
2552 * Two windows: a window on the left and a window on the right.
2553 * Mouse is hovered over the left window.
2554 * Next, we tap on the left window, where the cursor was last seen.
2555 *
2556 * After that, we inject one finger down onto the right window, and then a second finger down onto
2557 * the left window.
2558 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2559 * window (first), and then another on the left window (second).
2560 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2561 * In the buggy implementation, second finger down on the left window would cause a crash.
2562 */
2563TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2565 sp<FakeWindowHandle> leftWindow =
2566 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2567 leftWindow->setFrame(Rect(0, 0, 200, 200));
2568
2569 sp<FakeWindowHandle> rightWindow =
2570 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2571 rightWindow->setFrame(Rect(200, 0, 400, 200));
2572
2573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2574
2575 const int32_t mouseDeviceId = 6;
2576 const int32_t touchDeviceId = 4;
2577 // Hover over the left window. Keep the cursor there.
2578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2579 injectMotionEvent(mDispatcher,
2580 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2581 AINPUT_SOURCE_MOUSE)
2582 .deviceId(mouseDeviceId)
2583 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2584 .x(50)
2585 .y(50))
2586 .build()));
2587 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2588
2589 // Tap on left window
2590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2591 injectMotionEvent(mDispatcher,
2592 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2593 AINPUT_SOURCE_TOUCHSCREEN)
2594 .deviceId(touchDeviceId)
2595 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2596 .x(100)
2597 .y(100))
2598 .build()));
2599
2600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2601 injectMotionEvent(mDispatcher,
2602 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2603 AINPUT_SOURCE_TOUCHSCREEN)
2604 .deviceId(touchDeviceId)
2605 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2606 .x(100)
2607 .y(100))
2608 .build()));
2609 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2610 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2611 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2612
2613 // First finger down on right window
2614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2615 injectMotionEvent(mDispatcher,
2616 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2617 AINPUT_SOURCE_TOUCHSCREEN)
2618 .deviceId(touchDeviceId)
2619 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2620 .x(300)
2621 .y(100))
2622 .build()));
2623 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2624
2625 // Second finger down on the left window
2626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2627 injectMotionEvent(mDispatcher,
2628 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2629 .deviceId(touchDeviceId)
2630 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2631 .x(300)
2632 .y(100))
2633 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2634 .x(100)
2635 .y(100))
2636 .build()));
2637 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2638 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2639
2640 // No more events
2641 leftWindow->assertNoEvents();
2642 rightWindow->assertNoEvents();
2643}
2644
2645/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002646 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2647 * While the touch is down, new hover events from the stylus device should be ignored. After the
2648 * touch is gone, stylus hovering should start working again.
2649 */
2650TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2651 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2652 sp<FakeWindowHandle> window =
2653 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2654 window->setFrame(Rect(0, 0, 200, 200));
2655
2656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2657
2658 const int32_t stylusDeviceId = 5;
2659 const int32_t touchDeviceId = 4;
2660 // Start hovering with stylus
2661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2662 injectMotionEvent(mDispatcher,
2663 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2664 AINPUT_SOURCE_STYLUS)
2665 .deviceId(stylusDeviceId)
2666 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2667 .x(50)
2668 .y(50))
2669 .build()));
2670 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2671
2672 // Finger down on the window
2673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2674 injectMotionEvent(mDispatcher,
2675 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2676 AINPUT_SOURCE_TOUCHSCREEN)
2677 .deviceId(touchDeviceId)
2678 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2679 .x(100)
2680 .y(100))
2681 .build()));
2682 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2683 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2684
2685 // Try to continue hovering with stylus. Since we are already down, injection should fail
2686 ASSERT_EQ(InputEventInjectionResult::FAILED,
2687 injectMotionEvent(mDispatcher,
2688 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2689 AINPUT_SOURCE_STYLUS)
2690 .deviceId(stylusDeviceId)
2691 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2692 .x(50)
2693 .y(50))
2694 .build()));
2695 // No event should be sent. This event should be ignored because a pointer from another device
2696 // is already down.
2697
2698 // Lift up the finger
2699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2700 injectMotionEvent(mDispatcher,
2701 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2702 AINPUT_SOURCE_TOUCHSCREEN)
2703 .deviceId(touchDeviceId)
2704 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2705 .x(100)
2706 .y(100))
2707 .build()));
2708 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2709
2710 // Now that the touch is gone, stylus hovering should start working again
2711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2712 injectMotionEvent(mDispatcher,
2713 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2714 AINPUT_SOURCE_STYLUS)
2715 .deviceId(stylusDeviceId)
2716 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2717 .x(50)
2718 .y(50))
2719 .build()));
2720 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2721 // No more events
2722 window->assertNoEvents();
2723}
2724
2725/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002726 * A spy window above a window with no input channel.
2727 * Start hovering with a stylus device, and then tap with it.
2728 * Ensure spy window receives the entire sequence.
2729 */
2730TEST_F(InputDispatcherTest, StylusHoverAndDownNoInputChannel) {
2731 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2732 sp<FakeWindowHandle> spyWindow =
2733 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2734 spyWindow->setFrame(Rect(0, 0, 200, 200));
2735 spyWindow->setTrustedOverlay(true);
2736 spyWindow->setSpy(true);
2737 sp<FakeWindowHandle> window =
2738 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2739 window->setNoInputChannel(true);
2740 window->setFrame(Rect(0, 0, 200, 200));
2741
2742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2743
2744 NotifyMotionArgs args;
2745
2746 // Start hovering with stylus
2747 mDispatcher->notifyMotion(
2748 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2749 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2750 .build()));
2751 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2752 // Stop hovering
2753 mDispatcher->notifyMotion(
2754 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2755 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2756 .build()));
2757 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2758
2759 // Stylus touches down
2760 mDispatcher->notifyMotion(
2761 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_STYLUS)
2762 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2763 .build()));
2764 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2765
2766 // Stylus goes up
2767 mDispatcher->notifyMotion(
2768 &(args = MotionArgsBuilder(ACTION_UP, AINPUT_SOURCE_STYLUS)
2769 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2770 .build()));
2771 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_UP));
2772
2773 // Again hover
2774 mDispatcher->notifyMotion(
2775 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2776 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2777 .build()));
2778 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2779 // Stop hovering
2780 mDispatcher->notifyMotion(
2781 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2782 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2783 .build()));
2784 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2785
2786 // No more events
2787 spyWindow->assertNoEvents();
2788 window->assertNoEvents();
2789}
2790
2791/**
2792 * Start hovering with a mouse, and then tap with a touch device. Pilfer the touch stream.
2793 * Next, click with the mouse device. Both windows (spy and regular) should receive the new mouse
2794 * ACTION_DOWN event because that's a new gesture, and pilfering should no longer be active.
2795 * While the mouse is down, new move events from the touch device should be ignored.
2796 */
2797TEST_F(InputDispatcherTest, TouchPilferAndMouseMove) {
2798 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2799 sp<FakeWindowHandle> spyWindow =
2800 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2801 spyWindow->setFrame(Rect(0, 0, 200, 200));
2802 spyWindow->setTrustedOverlay(true);
2803 spyWindow->setSpy(true);
2804 sp<FakeWindowHandle> window =
2805 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2806 window->setFrame(Rect(0, 0, 200, 200));
2807
2808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2809
2810 const int32_t mouseDeviceId = 7;
2811 const int32_t touchDeviceId = 4;
2812 NotifyMotionArgs args;
2813
2814 // Hover a bit with mouse first
2815 mDispatcher->notifyMotion(&(
2816 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2817 .deviceId(mouseDeviceId)
2818 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2819 .build()));
2820 spyWindow->consumeMotionEvent(
2821 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2822 window->consumeMotionEvent(
2823 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2824
2825 // Start touching
2826 mDispatcher->notifyMotion(
2827 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2828 .deviceId(touchDeviceId)
2829 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2830 .build()));
2831 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2832 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2833 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2834 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2835
2836 mDispatcher->notifyMotion(
2837 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2838 .deviceId(touchDeviceId)
2839 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(55).y(55))
2840 .build()));
2841 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2842 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2843
2844 // Pilfer the stream
2845 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2846 window->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2847
2848 mDispatcher->notifyMotion(
2849 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2850 .deviceId(touchDeviceId)
2851 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
2852 .build()));
2853 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2854
2855 // Mouse down
2856 mDispatcher->notifyMotion(&(
2857 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2858 .deviceId(mouseDeviceId)
2859 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2860 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2861 .build()));
2862
2863 spyWindow->consumeMotionEvent(
2864 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId)));
2865 spyWindow->consumeMotionEvent(
2866 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2867 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2868
2869 mDispatcher->notifyMotion(&(
2870 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2871 .deviceId(mouseDeviceId)
2872 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2873 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2874 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2875 .build()));
2876 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2877 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2878
2879 // Mouse move!
2880 mDispatcher->notifyMotion(&(
2881 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_MOUSE)
2882 .deviceId(mouseDeviceId)
2883 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2884 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(110).y(110))
2885 .build()));
2886 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2887 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2888
2889 // Touch move!
2890 mDispatcher->notifyMotion(
2891 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2892 .deviceId(touchDeviceId)
2893 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(65).y(65))
2894 .build()));
2895
2896 // No more events
2897 spyWindow->assertNoEvents();
2898 window->assertNoEvents();
2899}
2900
2901/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002902 * On the display, have a single window, and also an area where there's no window.
2903 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2904 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2905 */
2906TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2907 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2908 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002909 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002910
2911 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2912 NotifyMotionArgs args;
2913
2914 // Touch down on the empty space
2915 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2916
2917 mDispatcher->waitForIdle();
2918 window->assertNoEvents();
2919
2920 // Now touch down on the window with another pointer
2921 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2922 mDispatcher->waitForIdle();
2923 window->consumeMotionDown();
2924}
2925
2926/**
2927 * Same test as above, but instead of touching the empty space, the first touch goes to
2928 * non-touchable window.
2929 */
2930TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2932 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002933 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002934 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2935 window1->setTouchable(false);
2936 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002937 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002938 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2939
2940 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2941
2942 NotifyMotionArgs args;
2943 // Touch down on the non-touchable window
2944 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2945
2946 mDispatcher->waitForIdle();
2947 window1->assertNoEvents();
2948 window2->assertNoEvents();
2949
2950 // Now touch down on the window with another pointer
2951 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2952 mDispatcher->waitForIdle();
2953 window2->consumeMotionDown();
2954}
2955
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002956/**
2957 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2958 * to the event time of the first ACTION_DOWN sent to the particular window.
2959 */
2960TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2961 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2962 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002963 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002964 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2965 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002966 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002967 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2968
2969 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2970
2971 NotifyMotionArgs args;
2972 // Touch down on the first window
2973 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2974
2975 mDispatcher->waitForIdle();
2976 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002977 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002978 window2->assertNoEvents();
2979 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2980 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2981 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2982
2983 // Now touch down on the window with another pointer
2984 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2985 mDispatcher->waitForIdle();
2986 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002987 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002988 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2989 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2990 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2991 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2992
2993 // Now move the pointer on the second window
2994 mDispatcher->notifyMotion(
2995 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2996 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002997 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002998
2999 // Now add new touch down on the second window
3000 mDispatcher->notifyMotion(
3001 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
3002 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003003 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003004
3005 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
3006 window1->consumeMotionMove();
3007 window1->assertNoEvents();
3008
3009 // Now move the pointer on the first window
3010 mDispatcher->notifyMotion(
3011 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
3012 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003013 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003014
3015 mDispatcher->notifyMotion(&(
3016 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
3017 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003018 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003019}
3020
Garfield Tandf26e862020-07-01 20:18:19 -07003021TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003022 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003023 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003024 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003025 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003026 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003027 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003028 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003029
3030 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3031
3032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
3033
3034 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003036 injectMotionEvent(mDispatcher,
3037 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3038 AINPUT_SOURCE_MOUSE)
3039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3040 .x(900)
3041 .y(400))
3042 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003043 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003044
3045 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003047 injectMotionEvent(mDispatcher,
3048 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3049 AINPUT_SOURCE_MOUSE)
3050 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3051 .x(300)
3052 .y(400))
3053 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003054 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3055 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003056
3057 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003059 injectMotionEvent(mDispatcher,
3060 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3061 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3062 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3063 .x(300)
3064 .y(400))
3065 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003066 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3067 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003068
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003070 injectMotionEvent(mDispatcher,
3071 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3072 AINPUT_SOURCE_MOUSE)
3073 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3074 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3075 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3076 .x(300)
3077 .y(400))
3078 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003079 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003081 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003082 injectMotionEvent(mDispatcher,
3083 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3084 AINPUT_SOURCE_MOUSE)
3085 .buttonState(0)
3086 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3087 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3088 .x(300)
3089 .y(400))
3090 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003091 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003092
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003094 injectMotionEvent(mDispatcher,
3095 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3096 .buttonState(0)
3097 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3098 .x(300)
3099 .y(400))
3100 .build()));
3101 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3102
3103 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003105 injectMotionEvent(mDispatcher,
3106 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3107 AINPUT_SOURCE_MOUSE)
3108 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3109 .x(900)
3110 .y(400))
3111 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003112 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003113
3114 // No more events
3115 windowLeft->assertNoEvents();
3116 windowRight->assertNoEvents();
3117}
3118
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003119/**
3120 * Put two fingers down (and don't release them) and click the mouse button.
3121 * The clicking of mouse is a new ACTION_DOWN event. Since it's from a different device, the
3122 * currently active gesture should be canceled, and the new one should proceed.
3123 */
3124TEST_F(InputDispatcherTest, TwoPointersDownMouseClick) {
3125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3126 sp<FakeWindowHandle> window =
3127 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3128 window->setFrame(Rect(0, 0, 600, 800));
3129
3130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3131
3132 const int32_t touchDeviceId = 4;
3133 const int32_t mouseDeviceId = 6;
3134 NotifyMotionArgs args;
3135
3136 // Two pointers down
3137 mDispatcher->notifyMotion(&(
3138 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3139 .deviceId(touchDeviceId)
3140 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3141 .build()));
3142
3143 mDispatcher->notifyMotion(&(
3144 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3145 .deviceId(touchDeviceId)
3146 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3147 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
3148 .build()));
3149 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
3150 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
3151
3152 // Inject a series of mouse events for a mouse click
3153 mDispatcher->notifyMotion(&(
3154 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3155 .deviceId(mouseDeviceId)
3156 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3157 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3158 .build()));
3159 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
3160 WithPointerCount(2u)));
3161 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
3162
3163 mDispatcher->notifyMotion(&(
3164 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
3165 .deviceId(mouseDeviceId)
3166 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3167 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3168 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3169 .build()));
3170 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
3171
3172 // Try to send more touch events while the mouse is down. Since it's a continuation of an
3173 // already canceled gesture, it should be ignored.
3174 mDispatcher->notifyMotion(&(
3175 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
3176 .deviceId(touchDeviceId)
3177 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(101).y(101))
3178 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(121).y(121))
3179 .build()));
3180 window->assertNoEvents();
3181}
3182
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003183TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
3184 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3185
3186 sp<FakeWindowHandle> spyWindow =
3187 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3188 spyWindow->setFrame(Rect(0, 0, 600, 800));
3189 spyWindow->setTrustedOverlay(true);
3190 spyWindow->setSpy(true);
3191 sp<FakeWindowHandle> window =
3192 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3193 window->setFrame(Rect(0, 0, 600, 800));
3194
3195 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3197
3198 // Send mouse cursor to the window
3199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3200 injectMotionEvent(mDispatcher,
3201 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3202 AINPUT_SOURCE_MOUSE)
3203 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3204 .x(100)
3205 .y(100))
3206 .build()));
3207
3208 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3209 WithSource(AINPUT_SOURCE_MOUSE)));
3210 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3211 WithSource(AINPUT_SOURCE_MOUSE)));
3212
3213 window->assertNoEvents();
3214 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003215}
3216
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003217TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
3218 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3219
3220 sp<FakeWindowHandle> spyWindow =
3221 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3222 spyWindow->setFrame(Rect(0, 0, 600, 800));
3223 spyWindow->setTrustedOverlay(true);
3224 spyWindow->setSpy(true);
3225 sp<FakeWindowHandle> window =
3226 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3227 window->setFrame(Rect(0, 0, 600, 800));
3228
3229 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3231
3232 // Send mouse cursor to the window
3233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3234 injectMotionEvent(mDispatcher,
3235 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3236 AINPUT_SOURCE_MOUSE)
3237 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3238 .x(100)
3239 .y(100))
3240 .build()));
3241
3242 // Move mouse cursor
3243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3244 injectMotionEvent(mDispatcher,
3245 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3246 AINPUT_SOURCE_MOUSE)
3247 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3248 .x(110)
3249 .y(110))
3250 .build()));
3251
3252 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3253 WithSource(AINPUT_SOURCE_MOUSE)));
3254 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3255 WithSource(AINPUT_SOURCE_MOUSE)));
3256 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3257 WithSource(AINPUT_SOURCE_MOUSE)));
3258 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3259 WithSource(AINPUT_SOURCE_MOUSE)));
3260 // Touch down on the window
3261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3262 injectMotionEvent(mDispatcher,
3263 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3264 AINPUT_SOURCE_TOUCHSCREEN)
3265 .deviceId(SECOND_DEVICE_ID)
3266 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3267 .x(200)
3268 .y(200))
3269 .build()));
3270 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3271 WithSource(AINPUT_SOURCE_MOUSE)));
3272 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3273 WithSource(AINPUT_SOURCE_MOUSE)));
3274 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3275 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3276 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3277 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3278
3279 // pilfer the motion, retaining the gesture on the spy window.
3280 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
3281 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3282 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3283
3284 // Touch UP on the window
3285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3286 injectMotionEvent(mDispatcher,
3287 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3288 AINPUT_SOURCE_TOUCHSCREEN)
3289 .deviceId(SECOND_DEVICE_ID)
3290 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3291 .x(200)
3292 .y(200))
3293 .build()));
3294 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3295 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3296
3297 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
3298 // to send a new gesture. It should again go to both windows (spy and the window below), just
3299 // like the first gesture did, before pilfering. The window configuration has not changed.
3300
3301 // One more tap - DOWN
3302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3303 injectMotionEvent(mDispatcher,
3304 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3305 AINPUT_SOURCE_TOUCHSCREEN)
3306 .deviceId(SECOND_DEVICE_ID)
3307 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3308 .x(250)
3309 .y(250))
3310 .build()));
3311 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3312 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3313 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3314 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3315
3316 // Touch UP on the window
3317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3318 injectMotionEvent(mDispatcher,
3319 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3320 AINPUT_SOURCE_TOUCHSCREEN)
3321 .deviceId(SECOND_DEVICE_ID)
3322 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3323 .x(250)
3324 .y(250))
3325 .build()));
3326 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3327 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3328 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3329 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3330
3331 window->assertNoEvents();
3332 spyWindow->assertNoEvents();
3333}
3334
Garfield Tandf26e862020-07-01 20:18:19 -07003335// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
3336// directly in this test.
3337TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003338 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003339 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003340 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003341 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003342
3343 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3344
3345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003348 injectMotionEvent(mDispatcher,
3349 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3350 AINPUT_SOURCE_MOUSE)
3351 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3352 .x(300)
3353 .y(400))
3354 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003355 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003356 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003358 injectMotionEvent(mDispatcher,
3359 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3360 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3361 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3362 .x(300)
3363 .y(400))
3364 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003365 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3366 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003367
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003369 injectMotionEvent(mDispatcher,
3370 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3371 AINPUT_SOURCE_MOUSE)
3372 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3373 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3374 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3375 .x(300)
3376 .y(400))
3377 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003378 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003379
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003380 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003381 injectMotionEvent(mDispatcher,
3382 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3383 AINPUT_SOURCE_MOUSE)
3384 .buttonState(0)
3385 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3386 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3387 .x(300)
3388 .y(400))
3389 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003390 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003391
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003393 injectMotionEvent(mDispatcher,
3394 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3395 .buttonState(0)
3396 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3397 .x(300)
3398 .y(400))
3399 .build()));
3400 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3401
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003403 injectMotionEvent(mDispatcher,
3404 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
3405 AINPUT_SOURCE_MOUSE)
3406 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3407 .x(300)
3408 .y(400))
3409 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003410 window->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003411}
3412
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003413/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003414 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
3415 * is generated.
3416 */
3417TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
3418 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3419 sp<FakeWindowHandle> window =
3420 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3421 window->setFrame(Rect(0, 0, 1200, 800));
3422
3423 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3424
3425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3426
3427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3428 injectMotionEvent(mDispatcher,
3429 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3430 AINPUT_SOURCE_MOUSE)
3431 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3432 .x(300)
3433 .y(400))
3434 .build()));
3435 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3436
3437 // Remove the window, but keep the channel.
3438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3439 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3440}
3441
3442/**
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003443 * If mouse is hovering when the touch goes down, the hovering should be stopped via HOVER_EXIT.
3444 */
3445TEST_F(InputDispatcherTest, TouchDownAfterMouseHover) {
3446 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3447 sp<FakeWindowHandle> window =
3448 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3449 window->setFrame(Rect(0, 0, 100, 100));
3450
3451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3452
3453 const int32_t mouseDeviceId = 7;
3454 const int32_t touchDeviceId = 4;
3455 NotifyMotionArgs args;
3456
3457 // Start hovering with the mouse
3458 mDispatcher->notifyMotion(
3459 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
3460 .deviceId(mouseDeviceId)
3461 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(10).y(10))
3462 .build()));
3463 window->consumeMotionEvent(
3464 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
3465
3466 // Touch goes down
3467 mDispatcher->notifyMotion(
3468 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3469 .deviceId(touchDeviceId)
3470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3471 .build()));
3472
3473 window->consumeMotionEvent(
3474 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
3475 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
3476}
3477
3478/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003479 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003480 * The tap causes a HOVER_EXIT event to be generated because the current event
3481 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003482 */
3483TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3484 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3485 sp<FakeWindowHandle> window =
3486 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3487 window->setFrame(Rect(0, 0, 100, 100));
3488
3489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3490
3491 // Inject a hover_move from mouse.
3492 NotifyMotionArgs motionArgs =
3493 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3494 ADISPLAY_ID_DEFAULT, {{50, 50}});
3495 motionArgs.xCursorPosition = 50;
3496 motionArgs.yCursorPosition = 50;
3497 mDispatcher->notifyMotion(&motionArgs);
3498 ASSERT_NO_FATAL_FAILURE(
3499 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3500 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003501
3502 // Tap on the window
3503 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3504 ADISPLAY_ID_DEFAULT, {{10, 10}});
3505 mDispatcher->notifyMotion(&motionArgs);
3506 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003507 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3508 WithSource(AINPUT_SOURCE_MOUSE))));
3509
3510 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003511 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3512 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3513
3514 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3515 ADISPLAY_ID_DEFAULT, {{10, 10}});
3516 mDispatcher->notifyMotion(&motionArgs);
3517 ASSERT_NO_FATAL_FAILURE(
3518 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3519 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3520}
3521
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003522TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3523 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3524 sp<FakeWindowHandle> windowDefaultDisplay =
3525 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3526 ADISPLAY_ID_DEFAULT);
3527 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3528 sp<FakeWindowHandle> windowSecondDisplay =
3529 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3530 SECOND_DISPLAY_ID);
3531 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3532
3533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3534 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3535
3536 // Set cursor position in window in default display and check that hover enter and move
3537 // events are generated.
3538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3539 injectMotionEvent(mDispatcher,
3540 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3541 AINPUT_SOURCE_MOUSE)
3542 .displayId(ADISPLAY_ID_DEFAULT)
3543 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3544 .x(300)
3545 .y(600))
3546 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003547 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003548
3549 // Remove all windows in secondary display and check that no event happens on window in
3550 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003551 mDispatcher->setInputWindows(
3552 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003553 windowDefaultDisplay->assertNoEvents();
3554
3555 // Move cursor position in window in default display and check that only hover move
3556 // event is generated and not hover enter event.
3557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3558 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3560 injectMotionEvent(mDispatcher,
3561 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3562 AINPUT_SOURCE_MOUSE)
3563 .displayId(ADISPLAY_ID_DEFAULT)
3564 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3565 .x(400)
3566 .y(700))
3567 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003568 windowDefaultDisplay->consumeMotionEvent(
3569 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3570 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003571 windowDefaultDisplay->assertNoEvents();
3572}
3573
Garfield Tan00f511d2019-06-12 16:55:40 -07003574TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003575 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003576
3577 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003578 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003579 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003580 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003581 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003582 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003583
3584 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3585
Arthur Hung72d8dc32020-03-28 00:48:39 +00003586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003587
3588 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3589 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003591 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003592 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003593 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003594 windowRight->assertNoEvents();
3595}
3596
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003597TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003598 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003599 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3600 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003601 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003602
Arthur Hung72d8dc32020-03-28 00:48:39 +00003603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003604 setFocusedWindow(window);
3605
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003606 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003607
3608 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3609 mDispatcher->notifyKey(&keyArgs);
3610
3611 // Window should receive key down event.
3612 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3613
3614 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3615 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003616 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003617 mDispatcher->notifyDeviceReset(&args);
3618 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3619 AKEY_EVENT_FLAG_CANCELED);
3620}
3621
3622TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003624 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3625 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003626
Arthur Hung72d8dc32020-03-28 00:48:39 +00003627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003628
3629 NotifyMotionArgs motionArgs =
3630 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3631 ADISPLAY_ID_DEFAULT);
3632 mDispatcher->notifyMotion(&motionArgs);
3633
3634 // Window should receive motion down event.
3635 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3636
3637 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3638 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003639 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003640 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003641 window->consumeMotionEvent(
3642 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003643}
3644
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003645TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003647 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3648 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003649 window->setFocusable(true);
3650
3651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3652 setFocusedWindow(window);
3653
3654 window->consumeFocusEvent(true);
3655
3656 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3657 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3658 const nsecs_t injectTime = keyArgs.eventTime;
3659 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3660 mDispatcher->notifyKey(&keyArgs);
3661 // The dispatching time should be always greater than or equal to intercept key timeout.
3662 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3663 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3664 std::chrono::nanoseconds(interceptKeyTimeout).count());
3665}
3666
3667TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003669 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3670 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003671 window->setFocusable(true);
3672
3673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3674 setFocusedWindow(window);
3675
3676 window->consumeFocusEvent(true);
3677
3678 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3679 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3680 mFakePolicy->setInterceptKeyTimeout(150ms);
3681 mDispatcher->notifyKey(&keyDown);
3682 mDispatcher->notifyKey(&keyUp);
3683
3684 // Window should receive key event immediately when same key up.
3685 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3686 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3687}
3688
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003689/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003690 * Two windows. First is a regular window. Second does not overlap with the first, and has
3691 * WATCH_OUTSIDE_TOUCH.
3692 * Both windows are owned by the same UID.
3693 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3694 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3695 */
3696TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3697 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3698 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3699 "First Window", ADISPLAY_ID_DEFAULT);
3700 window->setFrame(Rect{0, 0, 100, 100});
3701
3702 sp<FakeWindowHandle> outsideWindow =
3703 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3704 ADISPLAY_ID_DEFAULT);
3705 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3706 outsideWindow->setWatchOutsideTouch(true);
3707 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3709
3710 // Tap on first window.
3711 NotifyMotionArgs motionArgs =
3712 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3713 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3714 mDispatcher->notifyMotion(&motionArgs);
3715 window->consumeMotionDown();
3716 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3717 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3718 outsideWindow->consumeMotionEvent(
3719 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3720}
3721
3722/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003723 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3724 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3725 * ACTION_OUTSIDE event is sent per gesture.
3726 */
3727TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3728 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3729 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003730 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3731 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003732 window->setWatchOutsideTouch(true);
3733 window->setFrame(Rect{0, 0, 100, 100});
3734 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003735 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3736 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003737 secondWindow->setFrame(Rect{100, 100, 200, 200});
3738 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003739 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3740 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003741 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3743
3744 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3745 NotifyMotionArgs motionArgs =
3746 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3747 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3748 mDispatcher->notifyMotion(&motionArgs);
3749 window->assertNoEvents();
3750 secondWindow->assertNoEvents();
3751
3752 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3753 // Now, `window` should get ACTION_OUTSIDE.
3754 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3755 {PointF{-10, -10}, PointF{105, 105}});
3756 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003757 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3758 window->consumeMotionEvent(
3759 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003760 secondWindow->consumeMotionDown();
3761 thirdWindow->assertNoEvents();
3762
3763 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3764 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3765 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3766 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3767 mDispatcher->notifyMotion(&motionArgs);
3768 window->assertNoEvents();
3769 secondWindow->consumeMotionMove();
3770 thirdWindow->consumeMotionDown();
3771}
3772
Prabir Pradhan814fe082022-07-22 20:22:18 +00003773TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3774 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003775 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3776 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003777 window->setFocusable(true);
3778
3779 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3780 setFocusedWindow(window);
3781
3782 window->consumeFocusEvent(true);
3783
3784 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3785 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3786 mDispatcher->notifyKey(&keyDown);
3787 mDispatcher->notifyKey(&keyUp);
3788
3789 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3790 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3791
3792 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3793 mDispatcher->onWindowInfosChanged({}, {});
3794
3795 window->consumeFocusEvent(false);
3796
3797 mDispatcher->notifyKey(&keyDown);
3798 mDispatcher->notifyKey(&keyUp);
3799 window->assertNoEvents();
3800}
3801
Arthur Hung96483742022-11-15 03:30:48 +00003802TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3803 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3804 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3805 "Fake Window", ADISPLAY_ID_DEFAULT);
3806 // Ensure window is non-split and have some transform.
3807 window->setPreventSplitting(true);
3808 window->setWindowOffset(20, 40);
3809 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3810
3811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3813 {50, 50}))
3814 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3815 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3816
3817 const MotionEvent secondFingerDownEvent =
3818 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3819 .displayId(ADISPLAY_ID_DEFAULT)
3820 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003821 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3822 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003823 .build();
3824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3825 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3826 InputEventInjectionSync::WAIT_FOR_RESULT))
3827 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3828
3829 const MotionEvent* event = window->consumeMotion();
3830 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3831 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3832 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3833 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3834 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3835}
3836
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003837/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003838 * Ensure the correct coordinate spaces are used by InputDispatcher.
3839 *
3840 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3841 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3842 * space.
3843 */
3844class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3845public:
3846 void SetUp() override {
3847 InputDispatcherTest::SetUp();
3848 mDisplayInfos.clear();
3849 mWindowInfos.clear();
3850 }
3851
3852 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3853 gui::DisplayInfo info;
3854 info.displayId = displayId;
3855 info.transform = transform;
3856 mDisplayInfos.push_back(std::move(info));
3857 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3858 }
3859
3860 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3861 mWindowInfos.push_back(*windowHandle->getInfo());
3862 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3863 }
3864
3865 // Set up a test scenario where the display has a scaled projection and there are two windows
3866 // on the display.
3867 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3868 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3869 // respectively.
3870 ui::Transform displayTransform;
3871 displayTransform.set(2, 0, 0, 4);
3872 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3873
3874 std::shared_ptr<FakeApplicationHandle> application =
3875 std::make_shared<FakeApplicationHandle>();
3876
3877 // Add two windows to the display. Their frames are represented in the display space.
3878 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003879 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3880 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003881 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3882 addWindow(firstWindow);
3883
3884 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003885 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3886 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003887 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3888 addWindow(secondWindow);
3889 return {std::move(firstWindow), std::move(secondWindow)};
3890 }
3891
3892private:
3893 std::vector<gui::DisplayInfo> mDisplayInfos;
3894 std::vector<gui::WindowInfo> mWindowInfos;
3895};
3896
3897TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3898 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3899 // Send down to the first window. The point is represented in the display space. The point is
3900 // selected so that if the hit test was done with the transform applied to it, then it would
3901 // end up in the incorrect window.
3902 NotifyMotionArgs downMotionArgs =
3903 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3904 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3905 mDispatcher->notifyMotion(&downMotionArgs);
3906
3907 firstWindow->consumeMotionDown();
3908 secondWindow->assertNoEvents();
3909}
3910
3911// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3912// the event should be treated as being in the logical display space.
3913TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3914 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3915 // Send down to the first window. The point is represented in the logical display space. The
3916 // point is selected so that if the hit test was done in logical display space, then it would
3917 // end up in the incorrect window.
3918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3919 PointF{75 * 2, 55 * 4});
3920
3921 firstWindow->consumeMotionDown();
3922 secondWindow->assertNoEvents();
3923}
3924
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003925// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3926// event should be treated as being in the logical display space.
3927TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3928 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3929
3930 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3931 ui::Transform injectedEventTransform;
3932 injectedEventTransform.set(matrix);
3933 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
3934 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
3935
3936 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3937 .displayId(ADISPLAY_ID_DEFAULT)
3938 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003939 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003940 .x(untransformedPoint.x)
3941 .y(untransformedPoint.y))
3942 .build();
3943 event.transform(matrix);
3944
3945 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
3946 InputEventInjectionSync::WAIT_FOR_RESULT);
3947
3948 firstWindow->consumeMotionDown();
3949 secondWindow->assertNoEvents();
3950}
3951
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003952TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
3953 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3954
3955 // Send down to the second window.
3956 NotifyMotionArgs downMotionArgs =
3957 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3958 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
3959 mDispatcher->notifyMotion(&downMotionArgs);
3960
3961 firstWindow->assertNoEvents();
3962 const MotionEvent* event = secondWindow->consumeMotion();
3963 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
3964
3965 // Ensure that the events from the "getRaw" API are in logical display coordinates.
3966 EXPECT_EQ(300, event->getRawX(0));
3967 EXPECT_EQ(880, event->getRawY(0));
3968
3969 // Ensure that the x and y values are in the window's coordinate space.
3970 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
3971 // the logical display space. This will be the origin of the window space.
3972 EXPECT_EQ(100, event->getX(0));
3973 EXPECT_EQ(80, event->getY(0));
3974}
3975
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003976using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
3977 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003978
3979class TransferTouchFixture : public InputDispatcherTest,
3980 public ::testing::WithParamInterface<TransferFunction> {};
3981
3982TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07003983 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003984
3985 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003986 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003987 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3988 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003989 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003990 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003991 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3992 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003993 sp<FakeWindowHandle> wallpaper =
3994 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
3995 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003996 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00003997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003998
3999 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004000 NotifyMotionArgs downMotionArgs =
4001 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4002 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004003 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004004
Svet Ganov5d3bc372020-01-26 23:11:07 -08004005 // Only the first window should get the down event
4006 firstWindow->consumeMotionDown();
4007 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004008 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004009
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004010 // Transfer touch to the second window
4011 TransferFunction f = GetParam();
4012 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4013 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004014 // The first window gets cancel and the second gets down
4015 firstWindow->consumeMotionCancel();
4016 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004017 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004018
4019 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004020 NotifyMotionArgs upMotionArgs =
4021 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4022 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023 mDispatcher->notifyMotion(&upMotionArgs);
4024 // The first window gets no events and the second gets up
4025 firstWindow->assertNoEvents();
4026 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004027 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004028}
4029
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004030/**
4031 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4032 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4033 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4034 * natural to the user.
4035 * In this test, we are sending a pointer to both spy window and first window. We then try to
4036 * transfer touch to the second window. The dispatcher should identify the first window as the
4037 * one that should lose the gesture, and therefore the action should be to move the gesture from
4038 * the first window to the second.
4039 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4040 * the other API, as well.
4041 */
4042TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4044
4045 // Create a couple of windows + a spy window
4046 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004047 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004048 spyWindow->setTrustedOverlay(true);
4049 spyWindow->setSpy(true);
4050 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004051 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004052 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004053 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004054
4055 // Add the windows to the dispatcher
4056 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4057
4058 // Send down to the first window
4059 NotifyMotionArgs downMotionArgs =
4060 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4061 ADISPLAY_ID_DEFAULT);
4062 mDispatcher->notifyMotion(&downMotionArgs);
4063 // Only the first window and spy should get the down event
4064 spyWindow->consumeMotionDown();
4065 firstWindow->consumeMotionDown();
4066
4067 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4068 // if f === 'transferTouch'.
4069 TransferFunction f = GetParam();
4070 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4071 ASSERT_TRUE(success);
4072 // The first window gets cancel and the second gets down
4073 firstWindow->consumeMotionCancel();
4074 secondWindow->consumeMotionDown();
4075
4076 // Send up event to the second window
4077 NotifyMotionArgs upMotionArgs =
4078 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4079 ADISPLAY_ID_DEFAULT);
4080 mDispatcher->notifyMotion(&upMotionArgs);
4081 // The first window gets no events and the second+spy get up
4082 firstWindow->assertNoEvents();
4083 spyWindow->consumeMotionUp();
4084 secondWindow->consumeMotionUp();
4085}
4086
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004087TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004089
4090 PointF touchPoint = {10, 10};
4091
4092 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004093 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004094 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4095 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004096 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004097 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004098 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4099 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004100 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004101
4102 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004104
4105 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004106 NotifyMotionArgs downMotionArgs =
4107 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4108 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004109 mDispatcher->notifyMotion(&downMotionArgs);
4110 // Only the first window should get the down event
4111 firstWindow->consumeMotionDown();
4112 secondWindow->assertNoEvents();
4113
4114 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004115 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004116 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004117 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004118 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4119 // Only the first window should get the pointer down event
4120 firstWindow->consumeMotionPointerDown(1);
4121 secondWindow->assertNoEvents();
4122
4123 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004124 TransferFunction f = GetParam();
4125 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4126 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004127 // The first window gets cancel and the second gets down and pointer down
4128 firstWindow->consumeMotionCancel();
4129 secondWindow->consumeMotionDown();
4130 secondWindow->consumeMotionPointerDown(1);
4131
4132 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004133 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004134 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004135 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004136 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4137 // The first window gets nothing and the second gets pointer up
4138 firstWindow->assertNoEvents();
4139 secondWindow->consumeMotionPointerUp(1);
4140
4141 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004142 NotifyMotionArgs upMotionArgs =
4143 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4144 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004145 mDispatcher->notifyMotion(&upMotionArgs);
4146 // The first window gets nothing and the second gets up
4147 firstWindow->assertNoEvents();
4148 secondWindow->consumeMotionUp();
4149}
4150
Arthur Hungc539dbb2022-12-08 07:45:36 +00004151TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4152 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4153
4154 // Create a couple of windows
4155 sp<FakeWindowHandle> firstWindow =
4156 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4157 ADISPLAY_ID_DEFAULT);
4158 firstWindow->setDupTouchToWallpaper(true);
4159 sp<FakeWindowHandle> secondWindow =
4160 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4161 ADISPLAY_ID_DEFAULT);
4162 secondWindow->setDupTouchToWallpaper(true);
4163
4164 sp<FakeWindowHandle> wallpaper1 =
4165 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4166 wallpaper1->setIsWallpaper(true);
4167
4168 sp<FakeWindowHandle> wallpaper2 =
4169 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4170 wallpaper2->setIsWallpaper(true);
4171 // Add the windows to the dispatcher
4172 mDispatcher->setInputWindows(
4173 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4174
4175 // Send down to the first window
4176 NotifyMotionArgs downMotionArgs =
4177 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4178 ADISPLAY_ID_DEFAULT);
4179 mDispatcher->notifyMotion(&downMotionArgs);
4180
4181 // Only the first window should get the down event
4182 firstWindow->consumeMotionDown();
4183 secondWindow->assertNoEvents();
4184 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4185 wallpaper2->assertNoEvents();
4186
4187 // Transfer touch focus to the second window
4188 TransferFunction f = GetParam();
4189 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4190 ASSERT_TRUE(success);
4191
4192 // The first window gets cancel and the second gets down
4193 firstWindow->consumeMotionCancel();
4194 secondWindow->consumeMotionDown();
4195 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4196 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4197
4198 // Send up event to the second window
4199 NotifyMotionArgs upMotionArgs =
4200 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4201 ADISPLAY_ID_DEFAULT);
4202 mDispatcher->notifyMotion(&upMotionArgs);
4203 // The first window gets no events and the second gets up
4204 firstWindow->assertNoEvents();
4205 secondWindow->consumeMotionUp();
4206 wallpaper1->assertNoEvents();
4207 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4208}
4209
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004210// For the cases of single pointer touch and two pointers non-split touch, the api's
4211// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4212// for the case where there are multiple pointers split across several windows.
4213INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4214 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004215 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4216 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004217 return dispatcher->transferTouch(destChannelToken,
4218 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004219 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004220 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4221 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004222 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004223 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004224 }));
4225
Svet Ganov5d3bc372020-01-26 23:11:07 -08004226TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004228
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004229 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004230 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4231 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004232 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004234 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004235 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4236 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004237 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238
4239 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004241
4242 PointF pointInFirst = {300, 200};
4243 PointF pointInSecond = {300, 600};
4244
4245 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004246 NotifyMotionArgs firstDownMotionArgs =
4247 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4248 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004249 mDispatcher->notifyMotion(&firstDownMotionArgs);
4250 // Only the first window should get the down event
4251 firstWindow->consumeMotionDown();
4252 secondWindow->assertNoEvents();
4253
4254 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004255 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004256 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004257 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004258 mDispatcher->notifyMotion(&secondDownMotionArgs);
4259 // The first window gets a move and the second a down
4260 firstWindow->consumeMotionMove();
4261 secondWindow->consumeMotionDown();
4262
4263 // Transfer touch focus to the second window
4264 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4265 // The first window gets cancel and the new gets pointer down (it already saw down)
4266 firstWindow->consumeMotionCancel();
4267 secondWindow->consumeMotionPointerDown(1);
4268
4269 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004270 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004271 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004272 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004273 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4274 // The first window gets nothing and the second gets pointer up
4275 firstWindow->assertNoEvents();
4276 secondWindow->consumeMotionPointerUp(1);
4277
4278 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004279 NotifyMotionArgs upMotionArgs =
4280 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4281 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004282 mDispatcher->notifyMotion(&upMotionArgs);
4283 // The first window gets nothing and the second gets up
4284 firstWindow->assertNoEvents();
4285 secondWindow->consumeMotionUp();
4286}
4287
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004288// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4289// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4290// touch is not supported, so the touch should continue on those windows and the transferred-to
4291// window should get nothing.
4292TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4294
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004295 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004296 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4297 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004298 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004299
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004300 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004301 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4302 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004303 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004304
4305 // Add the windows to the dispatcher
4306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4307
4308 PointF pointInFirst = {300, 200};
4309 PointF pointInSecond = {300, 600};
4310
4311 // Send down to the first window
4312 NotifyMotionArgs firstDownMotionArgs =
4313 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4314 ADISPLAY_ID_DEFAULT, {pointInFirst});
4315 mDispatcher->notifyMotion(&firstDownMotionArgs);
4316 // Only the first window should get the down event
4317 firstWindow->consumeMotionDown();
4318 secondWindow->assertNoEvents();
4319
4320 // Send down to the second window
4321 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004322 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004323 {pointInFirst, pointInSecond});
4324 mDispatcher->notifyMotion(&secondDownMotionArgs);
4325 // The first window gets a move and the second a down
4326 firstWindow->consumeMotionMove();
4327 secondWindow->consumeMotionDown();
4328
4329 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004330 const bool transferred =
4331 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004332 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4333 ASSERT_FALSE(transferred);
4334 firstWindow->assertNoEvents();
4335 secondWindow->assertNoEvents();
4336
4337 // The rest of the dispatch should proceed as normal
4338 // Send pointer up to the second window
4339 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004340 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004341 {pointInFirst, pointInSecond});
4342 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4343 // The first window gets MOVE and the second gets pointer up
4344 firstWindow->consumeMotionMove();
4345 secondWindow->consumeMotionUp();
4346
4347 // Send up event to the first window
4348 NotifyMotionArgs upMotionArgs =
4349 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4350 ADISPLAY_ID_DEFAULT);
4351 mDispatcher->notifyMotion(&upMotionArgs);
4352 // The first window gets nothing and the second gets up
4353 firstWindow->consumeMotionUp();
4354 secondWindow->assertNoEvents();
4355}
4356
Arthur Hungabbb9d82021-09-01 14:52:30 +00004357// This case will create two windows and one mirrored window on the default display and mirror
4358// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4359// the windows info of second display before default display.
4360TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4361 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4362 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004363 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004364 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004365 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004366 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004367 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004368
4369 sp<FakeWindowHandle> mirrorWindowInPrimary =
4370 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4371 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004372
4373 sp<FakeWindowHandle> firstWindowInSecondary =
4374 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4375 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004376
4377 sp<FakeWindowHandle> secondWindowInSecondary =
4378 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4379 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004380
4381 // Update window info, let it find window handle of second display first.
4382 mDispatcher->setInputWindows(
4383 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4384 {ADISPLAY_ID_DEFAULT,
4385 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4386
4387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4388 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4389 {50, 50}))
4390 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4391
4392 // Window should receive motion event.
4393 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4394
4395 // Transfer touch focus
4396 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4397 secondWindowInPrimary->getToken()));
4398 // The first window gets cancel.
4399 firstWindowInPrimary->consumeMotionCancel();
4400 secondWindowInPrimary->consumeMotionDown();
4401
4402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4403 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4404 ADISPLAY_ID_DEFAULT, {150, 50}))
4405 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4406 firstWindowInPrimary->assertNoEvents();
4407 secondWindowInPrimary->consumeMotionMove();
4408
4409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4410 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4411 {150, 50}))
4412 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4413 firstWindowInPrimary->assertNoEvents();
4414 secondWindowInPrimary->consumeMotionUp();
4415}
4416
4417// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4418// 'transferTouch' api.
4419TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4420 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4421 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004422 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004423 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004424 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004425 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004426 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004427
4428 sp<FakeWindowHandle> mirrorWindowInPrimary =
4429 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4430 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004431
4432 sp<FakeWindowHandle> firstWindowInSecondary =
4433 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4434 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004435
4436 sp<FakeWindowHandle> secondWindowInSecondary =
4437 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4438 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004439
4440 // Update window info, let it find window handle of second display first.
4441 mDispatcher->setInputWindows(
4442 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4443 {ADISPLAY_ID_DEFAULT,
4444 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4445
4446 // Touch on second display.
4447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4448 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4450
4451 // Window should receive motion event.
4452 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4453
4454 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004455 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004456
4457 // The first window gets cancel.
4458 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4459 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4460
4461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4462 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4463 SECOND_DISPLAY_ID, {150, 50}))
4464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4465 firstWindowInPrimary->assertNoEvents();
4466 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4467
4468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4469 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4470 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4471 firstWindowInPrimary->assertNoEvents();
4472 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4473}
4474
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004475TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004476 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004477 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4478 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004479
Vishnu Nair47074b82020-08-14 11:54:47 -07004480 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004482 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004483
4484 window->consumeFocusEvent(true);
4485
4486 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4487 mDispatcher->notifyKey(&keyArgs);
4488
4489 // Window should receive key down event.
4490 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4491}
4492
4493TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004494 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004495 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4496 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004497
Arthur Hung72d8dc32020-03-28 00:48:39 +00004498 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004499
4500 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4501 mDispatcher->notifyKey(&keyArgs);
4502 mDispatcher->waitForIdle();
4503
4504 window->assertNoEvents();
4505}
4506
4507// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4508TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004509 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004510 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4511 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004512
Arthur Hung72d8dc32020-03-28 00:48:39 +00004513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004514
4515 // Send key
4516 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4517 mDispatcher->notifyKey(&keyArgs);
4518 // Send motion
4519 NotifyMotionArgs motionArgs =
4520 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4521 ADISPLAY_ID_DEFAULT);
4522 mDispatcher->notifyMotion(&motionArgs);
4523
4524 // Window should receive only the motion event
4525 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4526 window->assertNoEvents(); // Key event or focus event will not be received
4527}
4528
arthurhungea3f4fc2020-12-21 23:18:53 +08004529TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4530 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4531
arthurhungea3f4fc2020-12-21 23:18:53 +08004532 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004533 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4534 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004535 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004536
arthurhungea3f4fc2020-12-21 23:18:53 +08004537 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004538 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4539 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004540 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004541
4542 // Add the windows to the dispatcher
4543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4544
4545 PointF pointInFirst = {300, 200};
4546 PointF pointInSecond = {300, 600};
4547
4548 // Send down to the first window
4549 NotifyMotionArgs firstDownMotionArgs =
4550 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4551 ADISPLAY_ID_DEFAULT, {pointInFirst});
4552 mDispatcher->notifyMotion(&firstDownMotionArgs);
4553 // Only the first window should get the down event
4554 firstWindow->consumeMotionDown();
4555 secondWindow->assertNoEvents();
4556
4557 // Send down to the second window
4558 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004559 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004560 {pointInFirst, pointInSecond});
4561 mDispatcher->notifyMotion(&secondDownMotionArgs);
4562 // The first window gets a move and the second a down
4563 firstWindow->consumeMotionMove();
4564 secondWindow->consumeMotionDown();
4565
4566 // Send pointer cancel to the second window
4567 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004568 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004569 {pointInFirst, pointInSecond});
4570 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4571 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4572 // The first window gets move and the second gets cancel.
4573 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4574 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4575
4576 // Send up event.
4577 NotifyMotionArgs upMotionArgs =
4578 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4579 ADISPLAY_ID_DEFAULT);
4580 mDispatcher->notifyMotion(&upMotionArgs);
4581 // The first window gets up and the second gets nothing.
4582 firstWindow->consumeMotionUp();
4583 secondWindow->assertNoEvents();
4584}
4585
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004586TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4588
4589 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004590 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4592 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4593 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4594 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4595
Harry Cutts33476232023-01-30 19:57:29 +00004596 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004597 window->assertNoEvents();
4598 mDispatcher->waitForIdle();
4599}
4600
chaviwd1c23182019-12-20 18:44:56 -08004601class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004602public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004603 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004604 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004605 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004606 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004607 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004608 }
4609
chaviwd1c23182019-12-20 18:44:56 -08004610 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4611
4612 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4613 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4614 expectedDisplayId, expectedFlags);
4615 }
4616
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4618
4619 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4620
chaviwd1c23182019-12-20 18:44:56 -08004621 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4622 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4623 expectedDisplayId, expectedFlags);
4624 }
4625
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004626 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4627 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4628 expectedDisplayId, expectedFlags);
4629 }
4630
chaviwd1c23182019-12-20 18:44:56 -08004631 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4632 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4633 expectedDisplayId, expectedFlags);
4634 }
4635
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004636 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004637 mInputReceiver->consumeMotionEvent(
4638 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4639 WithDisplayId(expectedDisplayId),
4640 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004641 }
4642
Arthur Hungfbfa5722021-11-16 02:45:54 +00004643 void consumeMotionPointerDown(int32_t pointerIdx) {
4644 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4645 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4646 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004647 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004648 }
4649
Evan Rosky84f07f02021-04-16 10:42:42 -07004650 MotionEvent* consumeMotion() {
4651 InputEvent* event = mInputReceiver->consume();
4652 if (!event) {
4653 ADD_FAILURE() << "No event was produced";
4654 return nullptr;
4655 }
4656 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4657 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4658 return nullptr;
4659 }
4660 return static_cast<MotionEvent*>(event);
4661 }
4662
chaviwd1c23182019-12-20 18:44:56 -08004663 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4664
4665private:
4666 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004667};
4668
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004669using InputDispatcherMonitorTest = InputDispatcherTest;
4670
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004671/**
4672 * Two entities that receive touch: A window, and a global monitor.
4673 * The touch goes to the window, and then the window disappears.
4674 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4675 * for the monitor, as well.
4676 * 1. foregroundWindow
4677 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4678 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004679TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4681 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004682 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004683
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004684 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004685
4686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4688 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4689 {100, 200}))
4690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4691
4692 // Both the foreground window and the global monitor should receive the touch down
4693 window->consumeMotionDown();
4694 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4695
4696 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4697 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4698 ADISPLAY_ID_DEFAULT, {110, 200}))
4699 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4700
4701 window->consumeMotionMove();
4702 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4703
4704 // Now the foreground window goes away
4705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4706 window->consumeMotionCancel();
4707 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4708
4709 // If more events come in, there will be no more foreground window to send them to. This will
4710 // cause a cancel for the monitor, as well.
4711 ASSERT_EQ(InputEventInjectionResult::FAILED,
4712 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4713 ADISPLAY_ID_DEFAULT, {120, 200}))
4714 << "Injection should fail because the window was removed";
4715 window->assertNoEvents();
4716 // Global monitor now gets the cancel
4717 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4718}
4719
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004720TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004721 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004722 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4723 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004725
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004726 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004727
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004729 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004731 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004732 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004733}
4734
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004735TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4736 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004737
Chris Yea209fde2020-07-22 13:54:51 -07004738 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004739 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4740 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004742
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004744 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004746 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004747 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004748
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004749 // Pilfer pointers from the monitor.
4750 // This should not do anything and the window should continue to receive events.
4751 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004754 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4755 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004756 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004757
4758 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4759 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004760}
4761
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004762TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004763 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004764 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4765 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4767 window->setWindowOffset(20, 40);
4768 window->setWindowTransform(0, 1, -1, 0);
4769
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004770 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004771
4772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4773 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4775 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4776 MotionEvent* event = monitor.consumeMotion();
4777 // Even though window has transform, gesture monitor must not.
4778 ASSERT_EQ(ui::Transform(), event->getTransform());
4779}
4780
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004781TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004782 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004783 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004784
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004785 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004787 << "Injection should fail if there is a monitor, but no touchable window";
4788 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004789}
4790
chaviw81e2bb92019-12-18 15:03:51 -08004791TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004792 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004793 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4794 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004795
Arthur Hung72d8dc32020-03-28 00:48:39 +00004796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004797
4798 NotifyMotionArgs motionArgs =
4799 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4800 ADISPLAY_ID_DEFAULT);
4801
4802 mDispatcher->notifyMotion(&motionArgs);
4803 // Window should receive motion down event.
4804 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4805
4806 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004807 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004808 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4809 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4810 motionArgs.pointerCoords[0].getX() - 10);
4811
4812 mDispatcher->notifyMotion(&motionArgs);
4813 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004814 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004815}
4816
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004817/**
4818 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4819 * the device default right away. In the test scenario, we check both the default value,
4820 * and the action of enabling / disabling.
4821 */
4822TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004823 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004824 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4825 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004826 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004827
4828 // Set focused application.
4829 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004830 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004831
4832 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004834 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004835 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004836
4837 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004838 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004840 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004841
4842 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004843 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004844 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004845 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004846 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004848 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004849 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004850
4851 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004852 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004853 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004854 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004855
4856 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004857 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004858 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004859 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004860 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004862 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004863 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004864
4865 window->assertNoEvents();
4866}
4867
Gang Wange9087892020-01-07 12:17:14 -05004868TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004869 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004870 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4871 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004872
4873 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004874 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004875
Arthur Hung72d8dc32020-03-28 00:48:39 +00004876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004877 setFocusedWindow(window);
4878
Harry Cutts33476232023-01-30 19:57:29 +00004879 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004880
4881 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4882 mDispatcher->notifyKey(&keyArgs);
4883
4884 InputEvent* event = window->consume();
4885 ASSERT_NE(event, nullptr);
4886
4887 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4888 ASSERT_NE(verified, nullptr);
4889 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4890
4891 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4892 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4893 ASSERT_EQ(keyArgs.source, verified->source);
4894 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4895
4896 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4897
4898 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004899 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004900 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004901 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4902 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4903 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4904 ASSERT_EQ(0, verifiedKey.repeatCount);
4905}
4906
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004907TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004908 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004909 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4910 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004911
4912 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4913
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004914 ui::Transform transform;
4915 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4916
4917 gui::DisplayInfo displayInfo;
4918 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
4919 displayInfo.transform = transform;
4920
4921 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004922
4923 NotifyMotionArgs motionArgs =
4924 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4925 ADISPLAY_ID_DEFAULT);
4926 mDispatcher->notifyMotion(&motionArgs);
4927
4928 InputEvent* event = window->consume();
4929 ASSERT_NE(event, nullptr);
4930
4931 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4932 ASSERT_NE(verified, nullptr);
4933 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
4934
4935 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
4936 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
4937 EXPECT_EQ(motionArgs.source, verified->source);
4938 EXPECT_EQ(motionArgs.displayId, verified->displayId);
4939
4940 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
4941
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004942 const vec2 rawXY =
4943 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
4944 motionArgs.pointerCoords[0].getXYValue());
4945 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
4946 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004947 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004948 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004949 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004950 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
4951 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
4952}
4953
chaviw09c8d2d2020-08-24 15:48:26 -07004954/**
4955 * Ensure that separate calls to sign the same data are generating the same key.
4956 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
4957 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
4958 * tests.
4959 */
4960TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
4961 KeyEvent event = getTestKeyEvent();
4962 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4963
4964 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
4965 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
4966 ASSERT_EQ(hmac1, hmac2);
4967}
4968
4969/**
4970 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
4971 */
4972TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
4973 KeyEvent event = getTestKeyEvent();
4974 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4975 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
4976
4977 verifiedEvent.deviceId += 1;
4978 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4979
4980 verifiedEvent.source += 1;
4981 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4982
4983 verifiedEvent.eventTimeNanos += 1;
4984 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4985
4986 verifiedEvent.displayId += 1;
4987 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4988
4989 verifiedEvent.action += 1;
4990 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4991
4992 verifiedEvent.downTimeNanos += 1;
4993 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4994
4995 verifiedEvent.flags += 1;
4996 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4997
4998 verifiedEvent.keyCode += 1;
4999 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5000
5001 verifiedEvent.scanCode += 1;
5002 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5003
5004 verifiedEvent.metaState += 1;
5005 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5006
5007 verifiedEvent.repeatCount += 1;
5008 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5009}
5010
Vishnu Nair958da932020-08-21 17:12:37 -07005011TEST_F(InputDispatcherTest, SetFocusedWindow) {
5012 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5013 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005014 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005015 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005016 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005017 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5018
5019 // Top window is also focusable but is not granted focus.
5020 windowTop->setFocusable(true);
5021 windowSecond->setFocusable(true);
5022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5023 setFocusedWindow(windowSecond);
5024
5025 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5027 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005028
5029 // Focused window should receive event.
5030 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5031 windowTop->assertNoEvents();
5032}
5033
5034TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5036 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005037 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005038 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5039
5040 window->setFocusable(true);
5041 // Release channel for window is no longer valid.
5042 window->releaseChannel();
5043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5044 setFocusedWindow(window);
5045
5046 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005047 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5048 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005049
5050 // window channel is invalid, so it should not receive any input event.
5051 window->assertNoEvents();
5052}
5053
5054TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5055 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5056 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005057 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005058 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005059 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5060
Vishnu Nair958da932020-08-21 17:12:37 -07005061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5062 setFocusedWindow(window);
5063
5064 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005065 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5066 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005067
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005068 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005069 window->assertNoEvents();
5070}
5071
5072TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5073 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5074 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005075 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005076 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005077 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5079
5080 windowTop->setFocusable(true);
5081 windowSecond->setFocusable(true);
5082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5083 setFocusedWindow(windowTop);
5084 windowTop->consumeFocusEvent(true);
5085
5086 setFocusedWindow(windowSecond, windowTop);
5087 windowSecond->consumeFocusEvent(true);
5088 windowTop->consumeFocusEvent(false);
5089
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5091 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005092
5093 // Focused window should receive event.
5094 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5095}
5096
5097TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5098 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5099 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005100 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005101 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005102 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005103 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5104
5105 windowTop->setFocusable(true);
5106 windowSecond->setFocusable(true);
5107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5108 setFocusedWindow(windowSecond, windowTop);
5109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005110 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5111 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005112
5113 // Event should be dropped.
5114 windowTop->assertNoEvents();
5115 windowSecond->assertNoEvents();
5116}
5117
5118TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5119 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5120 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005121 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005122 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005123 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5124 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005125 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5126
5127 window->setFocusable(true);
5128 previousFocusedWindow->setFocusable(true);
5129 window->setVisible(false);
5130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5131 setFocusedWindow(previousFocusedWindow);
5132 previousFocusedWindow->consumeFocusEvent(true);
5133
5134 // Requesting focus on invisible window takes focus from currently focused window.
5135 setFocusedWindow(window);
5136 previousFocusedWindow->consumeFocusEvent(false);
5137
5138 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005140 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5141 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005142
5143 // Window does not get focus event or key down.
5144 window->assertNoEvents();
5145
5146 // Window becomes visible.
5147 window->setVisible(true);
5148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5149
5150 // Window receives focus event.
5151 window->consumeFocusEvent(true);
5152 // Focused window receives key down.
5153 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5154}
5155
Vishnu Nair599f1412021-06-21 10:39:58 -07005156TEST_F(InputDispatcherTest, DisplayRemoved) {
5157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5158 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005159 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005160 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5161
5162 // window is granted focus.
5163 window->setFocusable(true);
5164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5165 setFocusedWindow(window);
5166 window->consumeFocusEvent(true);
5167
5168 // When a display is removed window loses focus.
5169 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5170 window->consumeFocusEvent(false);
5171}
5172
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005173/**
5174 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5175 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5176 * of the 'slipperyEnterWindow'.
5177 *
5178 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5179 * a way so that the touched location is no longer covered by the top window.
5180 *
5181 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5182 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5183 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5184 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5185 * with ACTION_DOWN).
5186 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5187 * window moved itself away from the touched location and had Flag::SLIPPERY.
5188 *
5189 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5190 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5191 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5192 *
5193 * In this test, we ensure that the event received by the bottom window has
5194 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5195 */
5196TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005197 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5198 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005199
5200 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5201 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5202
5203 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005204 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005205 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005206 // Make sure this one overlaps the bottom window
5207 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5208 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5209 // one. Windows with the same owner are not considered to be occluding each other.
5210 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5211
5212 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005213 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005214 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5215
5216 mDispatcher->setInputWindows(
5217 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5218
5219 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5220 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5221 ADISPLAY_ID_DEFAULT, {{50, 50}});
5222 mDispatcher->notifyMotion(&args);
5223 slipperyExitWindow->consumeMotionDown();
5224 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5225 mDispatcher->setInputWindows(
5226 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5227
5228 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5229 ADISPLAY_ID_DEFAULT, {{51, 51}});
5230 mDispatcher->notifyMotion(&args);
5231
5232 slipperyExitWindow->consumeMotionCancel();
5233
5234 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5235 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5236}
5237
Garfield Tan1c7bc862020-01-28 13:24:04 -08005238class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5239protected:
5240 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5241 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5242
Chris Yea209fde2020-07-22 13:54:51 -07005243 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005244 sp<FakeWindowHandle> mWindow;
5245
5246 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005247 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005248 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005249 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005250 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5251 ASSERT_EQ(OK, mDispatcher->start());
5252
5253 setUpWindow();
5254 }
5255
5256 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005257 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005258 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005259
Vishnu Nair47074b82020-08-14 11:54:47 -07005260 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005261 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005262 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005263 mWindow->consumeFocusEvent(true);
5264 }
5265
Chris Ye2ad95392020-09-01 13:44:44 -07005266 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005267 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005268 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005269 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5270 mDispatcher->notifyKey(&keyArgs);
5271
5272 // Window should receive key down event.
5273 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5274 }
5275
5276 void expectKeyRepeatOnce(int32_t repeatCount) {
5277 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5278 InputEvent* repeatEvent = mWindow->consume();
5279 ASSERT_NE(nullptr, repeatEvent);
5280
5281 uint32_t eventType = repeatEvent->getType();
5282 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5283
5284 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5285 uint32_t eventAction = repeatKeyEvent->getAction();
5286 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5287 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5288 }
5289
Chris Ye2ad95392020-09-01 13:44:44 -07005290 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005291 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005292 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005293 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5294 mDispatcher->notifyKey(&keyArgs);
5295
5296 // Window should receive key down event.
5297 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005298 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005299 }
5300};
5301
5302TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005303 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005304 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5305 expectKeyRepeatOnce(repeatCount);
5306 }
5307}
5308
5309TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005310 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005311 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5312 expectKeyRepeatOnce(repeatCount);
5313 }
Harry Cutts33476232023-01-30 19:57:29 +00005314 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005315 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005316 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5317 expectKeyRepeatOnce(repeatCount);
5318 }
5319}
5320
5321TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005322 sendAndConsumeKeyDown(/*deviceId=*/1);
5323 expectKeyRepeatOnce(/*repeatCount=*/1);
5324 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005325 mWindow->assertNoEvents();
5326}
5327
5328TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005329 sendAndConsumeKeyDown(/*deviceId=*/1);
5330 expectKeyRepeatOnce(/*repeatCount=*/1);
5331 sendAndConsumeKeyDown(/*deviceId=*/2);
5332 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005333 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005334 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005335 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005336 expectKeyRepeatOnce(/*repeatCount=*/2);
5337 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005338 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005339 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005340 mWindow->assertNoEvents();
5341}
5342
5343TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005344 sendAndConsumeKeyDown(/*deviceId=*/1);
5345 expectKeyRepeatOnce(/*repeatCount=*/1);
5346 sendAndConsumeKeyDown(/*deviceId=*/2);
5347 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005348 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005349 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005350 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005351 mWindow->assertNoEvents();
5352}
5353
liushenxiang42232912021-05-21 20:24:09 +08005354TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5355 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005356 expectKeyRepeatOnce(/*repeatCount=*/1);
5357 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005358 mDispatcher->notifyDeviceReset(&args);
5359 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5360 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5361 mWindow->assertNoEvents();
5362}
5363
Garfield Tan1c7bc862020-01-28 13:24:04 -08005364TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Harry Cutts33476232023-01-30 19:57:29 +00005365 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005366 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5367 InputEvent* repeatEvent = mWindow->consume();
5368 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5369 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5370 IdGenerator::getSource(repeatEvent->getId()));
5371 }
5372}
5373
5374TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Harry Cutts33476232023-01-30 19:57:29 +00005375 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005376
5377 std::unordered_set<int32_t> idSet;
5378 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5379 InputEvent* repeatEvent = mWindow->consume();
5380 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5381 int32_t id = repeatEvent->getId();
5382 EXPECT_EQ(idSet.end(), idSet.find(id));
5383 idSet.insert(id);
5384 }
5385}
5386
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005387/* Test InputDispatcher for MultiDisplay */
5388class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5389public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005390 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005391 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005392
Chris Yea209fde2020-07-22 13:54:51 -07005393 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005394 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005395 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005396
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005397 // Set focus window for primary display, but focused display would be second one.
5398 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005399 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005401 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005402 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005403
Chris Yea209fde2020-07-22 13:54:51 -07005404 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005405 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005406 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005407 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005408 // Set focus display to second one.
5409 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5410 // Set focus window for second display.
5411 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005412 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005413 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005414 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005415 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005416 }
5417
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005418 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005419 InputDispatcherTest::TearDown();
5420
Chris Yea209fde2020-07-22 13:54:51 -07005421 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005422 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005423 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005424 windowInSecondary.clear();
5425 }
5426
5427protected:
Chris Yea209fde2020-07-22 13:54:51 -07005428 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005429 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005430 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005431 sp<FakeWindowHandle> windowInSecondary;
5432};
5433
5434TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5435 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5437 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5438 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005439 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005440 windowInSecondary->assertNoEvents();
5441
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005442 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5444 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005446 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005447 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005448}
5449
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005450TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005451 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5453 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005454 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005455 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005456 windowInSecondary->assertNoEvents();
5457
5458 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005460 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005461 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005462 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005463
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005464 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005465 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005466
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005467 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005468 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5469 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005470
5471 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005472 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005473 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005474 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005475 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005476 windowInSecondary->assertNoEvents();
5477}
5478
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005479// Test per-display input monitors for motion event.
5480TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005481 FakeMonitorReceiver monitorInPrimary =
5482 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5483 FakeMonitorReceiver monitorInSecondary =
5484 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005485
5486 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005490 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005491 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005492 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005493 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005494
5495 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5497 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005499 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005500 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005501 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005502 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005503
5504 // Test inject a non-pointer motion event.
5505 // If specific a display, it will dispatch to the focused window of particular display,
5506 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5508 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005510 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005511 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005512 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005513 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005514}
5515
5516// Test per-display input monitors for key event.
5517TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005518 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005519 FakeMonitorReceiver monitorInPrimary =
5520 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5521 FakeMonitorReceiver monitorInSecondary =
5522 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005523
5524 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5526 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005527 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005528 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005529 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005530 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005531}
5532
Vishnu Nair958da932020-08-21 17:12:37 -07005533TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5534 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005535 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005536 secondWindowInPrimary->setFocusable(true);
5537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5538 setFocusedWindow(secondWindowInPrimary);
5539 windowInPrimary->consumeFocusEvent(false);
5540 secondWindowInPrimary->consumeFocusEvent(true);
5541
5542 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5544 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005545 windowInPrimary->assertNoEvents();
5546 windowInSecondary->assertNoEvents();
5547 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5548}
5549
Arthur Hungdfd528e2021-12-08 13:23:04 +00005550TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5551 FakeMonitorReceiver monitorInPrimary =
5552 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5553 FakeMonitorReceiver monitorInSecondary =
5554 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5555
5556 // Test touch down on primary display.
5557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5560 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5561 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5562
5563 // Test touch down on second display.
5564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5565 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5567 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5568 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5569
5570 // Trigger cancel touch.
5571 mDispatcher->cancelCurrentTouch();
5572 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5573 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5574 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5575 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5576
5577 // Test inject a move motion event, no window/monitor should receive the event.
5578 ASSERT_EQ(InputEventInjectionResult::FAILED,
5579 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5580 ADISPLAY_ID_DEFAULT, {110, 200}))
5581 << "Inject motion event should return InputEventInjectionResult::FAILED";
5582 windowInPrimary->assertNoEvents();
5583 monitorInPrimary.assertNoEvents();
5584
5585 ASSERT_EQ(InputEventInjectionResult::FAILED,
5586 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5587 SECOND_DISPLAY_ID, {110, 200}))
5588 << "Inject motion event should return InputEventInjectionResult::FAILED";
5589 windowInSecondary->assertNoEvents();
5590 monitorInSecondary.assertNoEvents();
5591}
5592
Jackal Guof9696682018-10-05 12:23:23 +08005593class InputFilterTest : public InputDispatcherTest {
5594protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005595 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5596 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005597 NotifyMotionArgs motionArgs;
5598
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005599 motionArgs =
5600 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005601 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005602 motionArgs =
5603 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005604 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005605 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005606 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005607 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5608 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005609 } else {
5610 mFakePolicy->assertFilterInputEventWasNotCalled();
5611 }
5612 }
5613
5614 void testNotifyKey(bool expectToBeFiltered) {
5615 NotifyKeyArgs keyArgs;
5616
5617 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5618 mDispatcher->notifyKey(&keyArgs);
5619 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5620 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005621 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005622
5623 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005624 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005625 } else {
5626 mFakePolicy->assertFilterInputEventWasNotCalled();
5627 }
5628 }
5629};
5630
5631// Test InputFilter for MotionEvent
5632TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5633 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5634 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5635 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5636
5637 // Enable InputFilter
5638 mDispatcher->setInputFilterEnabled(true);
5639 // Test touch on both primary and second display, and check if both events are filtered.
5640 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5641 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5642
5643 // Disable InputFilter
5644 mDispatcher->setInputFilterEnabled(false);
5645 // Test touch on both primary and second display, and check if both events aren't filtered.
5646 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5647 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5648}
5649
5650// Test InputFilter for KeyEvent
5651TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5652 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5653 testNotifyKey(/*expectToBeFiltered*/ false);
5654
5655 // Enable InputFilter
5656 mDispatcher->setInputFilterEnabled(true);
5657 // Send a key event, and check if it is filtered.
5658 testNotifyKey(/*expectToBeFiltered*/ true);
5659
5660 // Disable InputFilter
5661 mDispatcher->setInputFilterEnabled(false);
5662 // Send a key event, and check if it isn't filtered.
5663 testNotifyKey(/*expectToBeFiltered*/ false);
5664}
5665
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005666// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5667// logical display coordinate space.
5668TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5669 ui::Transform firstDisplayTransform;
5670 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5671 ui::Transform secondDisplayTransform;
5672 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5673
5674 std::vector<gui::DisplayInfo> displayInfos(2);
5675 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5676 displayInfos[0].transform = firstDisplayTransform;
5677 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5678 displayInfos[1].transform = secondDisplayTransform;
5679
5680 mDispatcher->onWindowInfosChanged({}, displayInfos);
5681
5682 // Enable InputFilter
5683 mDispatcher->setInputFilterEnabled(true);
5684
5685 // Ensure the correct transforms are used for the displays.
5686 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5687 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5688}
5689
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005690class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5691protected:
5692 virtual void SetUp() override {
5693 InputDispatcherTest::SetUp();
5694
5695 /**
5696 * We don't need to enable input filter to test the injected event policy, but we enabled it
5697 * here to make the tests more realistic, since this policy only matters when inputfilter is
5698 * on.
5699 */
5700 mDispatcher->setInputFilterEnabled(true);
5701
5702 std::shared_ptr<InputApplicationHandle> application =
5703 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005704 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5705 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005706
5707 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5708 mWindow->setFocusable(true);
5709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5710 setFocusedWindow(mWindow);
5711 mWindow->consumeFocusEvent(true);
5712 }
5713
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005714 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5715 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005716 KeyEvent event;
5717
5718 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5719 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5720 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005721 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005722 const int32_t additionalPolicyFlags =
5723 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005725 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005726 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5727 policyFlags | additionalPolicyFlags));
5728
5729 InputEvent* received = mWindow->consume();
5730 ASSERT_NE(nullptr, received);
5731 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005732 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5733 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5734 ASSERT_EQ(flags, keyEvent.getFlags());
5735 }
5736
5737 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5738 int32_t flags) {
5739 MotionEvent event;
5740 PointerProperties pointerProperties[1];
5741 PointerCoords pointerCoords[1];
5742 pointerProperties[0].clear();
5743 pointerProperties[0].id = 0;
5744 pointerCoords[0].clear();
5745 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5746 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5747
5748 ui::Transform identityTransform;
5749 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5750 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5751 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5752 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5753 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005754 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005755 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005756 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5757
5758 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005760 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005761 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5762 policyFlags | additionalPolicyFlags));
5763
5764 InputEvent* received = mWindow->consume();
5765 ASSERT_NE(nullptr, received);
5766 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5767 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5768 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5769 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005770 }
5771
5772private:
5773 sp<FakeWindowHandle> mWindow;
5774};
5775
5776TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005777 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5778 // filter. Without it, the event will no different from a regularly injected event, and the
5779 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005780 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5781 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005782}
5783
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005784TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005785 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005786 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005787 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5788}
5789
5790TEST_F(InputFilterInjectionPolicyTest,
5791 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5792 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005793 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005794 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005795}
5796
5797TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005798 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5799 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005800}
5801
chaviwfd6d3512019-03-25 13:23:49 -07005802class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005803 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005804 InputDispatcherTest::SetUp();
5805
Chris Yea209fde2020-07-22 13:54:51 -07005806 std::shared_ptr<FakeApplicationHandle> application =
5807 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005808 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005809 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005810 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005811
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005812 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005813 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005814 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005815
5816 // Set focused application.
5817 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005818 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005819
5820 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005822 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005823 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005824 }
5825
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005826 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005827 InputDispatcherTest::TearDown();
5828
5829 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005830 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005831 }
5832
5833protected:
5834 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005835 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005836 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005837};
5838
5839// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5840// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5841// the onPointerDownOutsideFocus callback.
5842TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5845 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005847 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005848
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005849 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005850 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5851}
5852
5853// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5854// DOWN on the window that doesn't have focus. Ensure no window received the
5855// onPointerDownOutsideFocus callback.
5856TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005858 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005860 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005861
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005862 ASSERT_TRUE(mDispatcher->waitForIdle());
5863 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005864}
5865
5866// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5867// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5868TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5870 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005871 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005872 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005873
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005874 ASSERT_TRUE(mDispatcher->waitForIdle());
5875 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005876}
5877
5878// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5879// DOWN on the window that already has focus. Ensure no window received the
5880// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005881TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005883 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005884 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005885 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005886 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005887
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005888 ASSERT_TRUE(mDispatcher->waitForIdle());
5889 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005890}
5891
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005892// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5893// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5894TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5895 const MotionEvent event =
5896 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5897 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005898 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005899 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
5900 .build();
5901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
5902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5903 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
5904
5905 ASSERT_TRUE(mDispatcher->waitForIdle());
5906 mFakePolicy->assertOnPointerDownWasNotCalled();
5907 // Ensure that the unfocused window did not receive any FOCUS events.
5908 mUnfocusedWindow->assertNoEvents();
5909}
5910
chaviwaf87b3e2019-10-01 16:59:28 -07005911// These tests ensures we can send touch events to a single client when there are multiple input
5912// windows that point to the same client token.
5913class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
5914 virtual void SetUp() override {
5915 InputDispatcherTest::SetUp();
5916
Chris Yea209fde2020-07-22 13:54:51 -07005917 std::shared_ptr<FakeApplicationHandle> application =
5918 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005919 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
5920 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07005921 mWindow1->setFrame(Rect(0, 0, 100, 100));
5922
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005923 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
5924 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07005925 mWindow2->setFrame(Rect(100, 100, 200, 200));
5926
Arthur Hung72d8dc32020-03-28 00:48:39 +00005927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07005928 }
5929
5930protected:
5931 sp<FakeWindowHandle> mWindow1;
5932 sp<FakeWindowHandle> mWindow2;
5933
5934 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05005935 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07005936 vec2 vals = windowInfo->transform.transform(point.x, point.y);
5937 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07005938 }
5939
5940 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
5941 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005942 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07005943 InputEvent* event = window->consume();
5944
5945 ASSERT_NE(nullptr, event) << name.c_str()
5946 << ": consumer should have returned non-NULL event.";
5947
5948 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
5949 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
5950 << " event, got " << inputEventTypeToString(event->getType()) << " event";
5951
5952 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005953 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08005954 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07005955
5956 for (size_t i = 0; i < points.size(); i++) {
5957 float expectedX = points[i].x;
5958 float expectedY = points[i].y;
5959
5960 EXPECT_EQ(expectedX, motionEvent.getX(i))
5961 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
5962 << ", got " << motionEvent.getX(i);
5963 EXPECT_EQ(expectedY, motionEvent.getY(i))
5964 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
5965 << ", got " << motionEvent.getY(i);
5966 }
5967 }
chaviw9eaa22c2020-07-01 16:21:27 -07005968
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005969 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07005970 std::vector<PointF> expectedPoints) {
5971 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
5972 ADISPLAY_ID_DEFAULT, touchedPoints);
5973 mDispatcher->notifyMotion(&motionArgs);
5974
5975 // Always consume from window1 since it's the window that has the InputReceiver
5976 consumeMotionEvent(mWindow1, action, expectedPoints);
5977 }
chaviwaf87b3e2019-10-01 16:59:28 -07005978};
5979
5980TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
5981 // Touch Window 1
5982 PointF touchedPoint = {10, 10};
5983 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005984 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005985
5986 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005987 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005988
5989 // Touch Window 2
5990 touchedPoint = {150, 150};
5991 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005992 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005993}
5994
chaviw9eaa22c2020-07-01 16:21:27 -07005995TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
5996 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07005997 mWindow2->setWindowScale(0.5f, 0.5f);
5998
5999 // Touch Window 1
6000 PointF touchedPoint = {10, 10};
6001 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006002 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006003 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006004 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006005
6006 // Touch Window 2
6007 touchedPoint = {150, 150};
6008 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006009 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
6010 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006011
chaviw9eaa22c2020-07-01 16:21:27 -07006012 // Update the transform so rotation is set
6013 mWindow2->setWindowTransform(0, -1, 1, 0);
6014 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
6015 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006016}
6017
chaviw9eaa22c2020-07-01 16:21:27 -07006018TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006019 mWindow2->setWindowScale(0.5f, 0.5f);
6020
6021 // Touch Window 1
6022 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6023 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006024 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006025
6026 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006027 touchedPoints.push_back(PointF{150, 150});
6028 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006029 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006030
chaviw9eaa22c2020-07-01 16:21:27 -07006031 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006032 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006033 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006034
chaviw9eaa22c2020-07-01 16:21:27 -07006035 // Update the transform so rotation is set for Window 2
6036 mWindow2->setWindowTransform(0, -1, 1, 0);
6037 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006038 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006039}
6040
chaviw9eaa22c2020-07-01 16:21:27 -07006041TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006042 mWindow2->setWindowScale(0.5f, 0.5f);
6043
6044 // Touch Window 1
6045 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6046 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006047 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006048
6049 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006050 touchedPoints.push_back(PointF{150, 150});
6051 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006052
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006053 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006054
6055 // Move both windows
6056 touchedPoints = {{20, 20}, {175, 175}};
6057 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6058 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6059
chaviw9eaa22c2020-07-01 16:21:27 -07006060 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006061
chaviw9eaa22c2020-07-01 16:21:27 -07006062 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006063 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006064 expectedPoints.pop_back();
6065
6066 // Touch Window 2
6067 mWindow2->setWindowTransform(0, -1, 1, 0);
6068 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006069 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006070
6071 // Move both windows
6072 touchedPoints = {{20, 20}, {175, 175}};
6073 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6074 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6075
6076 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006077}
6078
6079TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6080 mWindow1->setWindowScale(0.5f, 0.5f);
6081
6082 // Touch Window 1
6083 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6084 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006085 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006086
6087 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006088 touchedPoints.push_back(PointF{150, 150});
6089 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006090
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006091 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006092
6093 // Move both windows
6094 touchedPoints = {{20, 20}, {175, 175}};
6095 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6096 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6097
chaviw9eaa22c2020-07-01 16:21:27 -07006098 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006099}
6100
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006101class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6102 virtual void SetUp() override {
6103 InputDispatcherTest::SetUp();
6104
Chris Yea209fde2020-07-22 13:54:51 -07006105 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006106 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006107 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6108 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006109 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006110 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006111 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006112
6113 // Set focused application.
6114 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6115
6116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006117 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006118 mWindow->consumeFocusEvent(true);
6119 }
6120
6121 virtual void TearDown() override {
6122 InputDispatcherTest::TearDown();
6123 mWindow.clear();
6124 }
6125
6126protected:
Chris Yea209fde2020-07-22 13:54:51 -07006127 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006128 sp<FakeWindowHandle> mWindow;
6129 static constexpr PointF WINDOW_LOCATION = {20, 20};
6130
6131 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006133 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6134 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006136 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6137 WINDOW_LOCATION));
6138 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006139
6140 sp<FakeWindowHandle> addSpyWindow() {
6141 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006142 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006143 spy->setTrustedOverlay(true);
6144 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006145 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006146 spy->setDispatchingTimeout(30ms);
6147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6148 return spy;
6149 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006150};
6151
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006152// Send a tap and respond, which should not cause an ANR.
6153TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6154 tapOnWindow();
6155 mWindow->consumeMotionDown();
6156 mWindow->consumeMotionUp();
6157 ASSERT_TRUE(mDispatcher->waitForIdle());
6158 mFakePolicy->assertNotifyAnrWasNotCalled();
6159}
6160
6161// Send a regular key and respond, which should not cause an ANR.
6162TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006164 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6165 ASSERT_TRUE(mDispatcher->waitForIdle());
6166 mFakePolicy->assertNotifyAnrWasNotCalled();
6167}
6168
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006169TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6170 mWindow->setFocusable(false);
6171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6172 mWindow->consumeFocusEvent(false);
6173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006174 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006175 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6176 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6177 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006178 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006179 // Key will not go to window because we have no focused window.
6180 // The 'no focused window' ANR timer should start instead.
6181
6182 // Now, the focused application goes away.
6183 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6184 // The key should get dropped and there should be no ANR.
6185
6186 ASSERT_TRUE(mDispatcher->waitForIdle());
6187 mFakePolicy->assertNotifyAnrWasNotCalled();
6188}
6189
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006190// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006191// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6192// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006193TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006195 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6196 WINDOW_LOCATION));
6197
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006198 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6199 ASSERT_TRUE(sequenceNum);
6200 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006201 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006202
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006204 mWindow->consumeMotionEvent(
6205 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006206 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006207 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006208}
6209
6210// Send a key to the app and have the app not respond right away.
6211TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6212 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006213 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006214 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6215 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006216 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006217 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006218 ASSERT_TRUE(mDispatcher->waitForIdle());
6219}
6220
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006221// We have a focused application, but no focused window
6222TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006223 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6225 mWindow->consumeFocusEvent(false);
6226
6227 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006229 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6230 WINDOW_LOCATION));
6231 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6232 mDispatcher->waitForIdle();
6233 mFakePolicy->assertNotifyAnrWasNotCalled();
6234
6235 // Once a focused event arrives, we get an ANR for this application
6236 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6237 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006238 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006239 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6240 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006241 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006242 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006243 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006244 ASSERT_TRUE(mDispatcher->waitForIdle());
6245}
6246
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006247/**
6248 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6249 * there will not be an ANR.
6250 */
6251TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6252 mWindow->setFocusable(false);
6253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6254 mWindow->consumeFocusEvent(false);
6255
6256 KeyEvent event;
6257 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6258 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6259
6260 // Define a valid key down event that is stale (too old).
6261 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6262 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006263 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006264
6265 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6266
6267 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006268 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006269 InputEventInjectionSync::WAIT_FOR_RESULT,
6270 INJECT_EVENT_TIMEOUT, policyFlags);
6271 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6272 << "Injection should fail because the event is stale";
6273
6274 ASSERT_TRUE(mDispatcher->waitForIdle());
6275 mFakePolicy->assertNotifyAnrWasNotCalled();
6276 mWindow->assertNoEvents();
6277}
6278
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006279// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006280// Make sure that we don't notify policy twice about the same ANR.
6281TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006282 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6284 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285
6286 // Once a focused event arrives, we get an ANR for this application
6287 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6288 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006289 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006290 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6291 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006292 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006293 const std::chrono::duration appTimeout =
6294 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6295 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006296
Vishnu Naire4df8752022-09-08 09:17:55 -07006297 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006298 // ANR should not be raised again. It is up to policy to do that if it desires.
6299 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006300
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006301 // If we now get a focused window, the ANR should stop, but the policy handles that via
6302 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303 ASSERT_TRUE(mDispatcher->waitForIdle());
6304}
6305
6306// We have a focused application, but no focused window
6307TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006308 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6310 mWindow->consumeFocusEvent(false);
6311
6312 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006313 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006314 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006315 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6316 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006317
Vishnu Naire4df8752022-09-08 09:17:55 -07006318 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6319 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320
6321 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006322 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323 ASSERT_TRUE(mDispatcher->waitForIdle());
6324 mWindow->assertNoEvents();
6325}
6326
6327/**
6328 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6329 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6330 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6331 * the ANR mechanism should still work.
6332 *
6333 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6334 * DOWN event, while not responding on the second one.
6335 */
6336TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6337 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6338 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6339 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6340 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6341 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006342 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006343
6344 // Now send ACTION_UP, with identical timestamp
6345 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6346 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6347 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6348 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006349 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006350
6351 // We have now sent down and up. Let's consume first event and then ANR on the second.
6352 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6353 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006354 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006355}
6356
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006357// A spy window can receive an ANR
6358TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6359 sp<FakeWindowHandle> spy = addSpyWindow();
6360
6361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6362 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6363 WINDOW_LOCATION));
6364 mWindow->consumeMotionDown();
6365
6366 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6367 ASSERT_TRUE(sequenceNum);
6368 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006369 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006370
6371 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006372 spy->consumeMotionEvent(
6373 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006374 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006375 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006376}
6377
6378// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006379// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006380TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6381 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006382
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006383 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6384 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006385 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006387
6388 // Stuck on the ACTION_UP
6389 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006390 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006391
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006392 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006393 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006394 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6395 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006396
6397 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6398 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006399 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006400 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006401 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006402}
6403
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006404// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006405// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006406TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6407 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006408
6409 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006410 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6411 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006412
6413 mWindow->consumeMotionDown();
6414 // Stuck on the ACTION_UP
6415 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006416 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006417
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006418 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006419 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006420 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6421 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006422
6423 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6424 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006425 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006426 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006427 spy->assertNoEvents();
6428}
6429
6430TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6431 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6432
6433 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6434
6435 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6436 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6437 WINDOW_LOCATION));
6438
6439 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6440 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6441 ASSERT_TRUE(consumeSeq);
6442
Prabir Pradhanedd96402022-02-15 01:46:16 -08006443 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006444
6445 monitor.finishEvent(*consumeSeq);
6446 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6447
6448 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006449 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006450}
6451
6452// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6453// process events, you don't get an anr. When the window later becomes unresponsive again, you
6454// get an ANR again.
6455// 1. tap -> block on ACTION_UP -> receive ANR
6456// 2. consume all pending events (= queue becomes healthy again)
6457// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6458TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6459 tapOnWindow();
6460
6461 mWindow->consumeMotionDown();
6462 // Block on ACTION_UP
6463 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006464 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006465 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6466 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006467 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006468 mWindow->assertNoEvents();
6469
6470 tapOnWindow();
6471 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006472 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006473 mWindow->consumeMotionUp();
6474
6475 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006476 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006477 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006478 mWindow->assertNoEvents();
6479}
6480
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006481// If a connection remains unresponsive for a while, make sure policy is only notified once about
6482// it.
6483TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6486 WINDOW_LOCATION));
6487
6488 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006489 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006490 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006491 // 'notifyConnectionUnresponsive' should only be called once per connection
6492 mFakePolicy->assertNotifyAnrWasNotCalled();
6493 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006494 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006495 mWindow->consumeMotionEvent(
6496 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006497 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006498 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006499 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006500 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006501}
6502
6503/**
6504 * If a window is processing a motion event, and then a key event comes in, the key event should
6505 * not to to the focused window until the motion is processed.
6506 *
6507 * Warning!!!
6508 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6509 * and the injection timeout that we specify when injecting the key.
6510 * We must have the injection timeout (10ms) be smaller than
6511 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6512 *
6513 * If that value changes, this test should also change.
6514 */
6515TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6516 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6518
6519 tapOnWindow();
6520 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6521 ASSERT_TRUE(downSequenceNum);
6522 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6523 ASSERT_TRUE(upSequenceNum);
6524 // Don't finish the events yet, and send a key
6525 // Injection will "succeed" because we will eventually give up and send the key to the focused
6526 // window even if motions are still being processed. But because the injection timeout is short,
6527 // we will receive INJECTION_TIMED_OUT as the result.
6528
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006529 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006530 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006531 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6532 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006533 // Key will not be sent to the window, yet, because the window is still processing events
6534 // and the key remains pending, waiting for the touch events to be processed
6535 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6536 ASSERT_FALSE(keySequenceNum);
6537
6538 std::this_thread::sleep_for(500ms);
6539 // if we wait long enough though, dispatcher will give up, and still send the key
6540 // to the focused window, even though we have not yet finished the motion event
6541 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6542 mWindow->finishEvent(*downSequenceNum);
6543 mWindow->finishEvent(*upSequenceNum);
6544}
6545
6546/**
6547 * If a window is processing a motion event, and then a key event comes in, the key event should
6548 * not go to the focused window until the motion is processed.
6549 * If then a new motion comes in, then the pending key event should be going to the currently
6550 * focused window right away.
6551 */
6552TEST_F(InputDispatcherSingleWindowAnr,
6553 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6554 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6556
6557 tapOnWindow();
6558 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6559 ASSERT_TRUE(downSequenceNum);
6560 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6561 ASSERT_TRUE(upSequenceNum);
6562 // Don't finish the events yet, and send a key
6563 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006565 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6566 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006567 // At this point, key is still pending, and should not be sent to the application yet.
6568 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6569 ASSERT_FALSE(keySequenceNum);
6570
6571 // Now tap down again. It should cause the pending key to go to the focused window right away.
6572 tapOnWindow();
6573 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6574 // the other events yet. We can finish events in any order.
6575 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6576 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6577 mWindow->consumeMotionDown();
6578 mWindow->consumeMotionUp();
6579 mWindow->assertNoEvents();
6580}
6581
6582class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6583 virtual void SetUp() override {
6584 InputDispatcherTest::SetUp();
6585
Chris Yea209fde2020-07-22 13:54:51 -07006586 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006587 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006588 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6589 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006590 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006591 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006592 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006593
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006594 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6595 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006596 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006597 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006598
6599 // Set focused application.
6600 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006601 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006602
6603 // Expect one focus window exist in display.
6604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006605 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006606 mFocusedWindow->consumeFocusEvent(true);
6607 }
6608
6609 virtual void TearDown() override {
6610 InputDispatcherTest::TearDown();
6611
6612 mUnfocusedWindow.clear();
6613 mFocusedWindow.clear();
6614 }
6615
6616protected:
Chris Yea209fde2020-07-22 13:54:51 -07006617 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006618 sp<FakeWindowHandle> mUnfocusedWindow;
6619 sp<FakeWindowHandle> mFocusedWindow;
6620 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6621 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6622 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6623
6624 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6625
6626 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6627
6628private:
6629 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006631 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6632 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006634 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6635 location));
6636 }
6637};
6638
6639// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6640// should be ANR'd first.
6641TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006643 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6644 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006645 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006646 mFocusedWindow->consumeMotionDown();
6647 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006648 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006649 // We consumed all events, so no ANR
6650 ASSERT_TRUE(mDispatcher->waitForIdle());
6651 mFakePolicy->assertNotifyAnrWasNotCalled();
6652
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6655 FOCUSED_WINDOW_LOCATION));
6656 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6657 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006658
6659 const std::chrono::duration timeout =
6660 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006661 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006662 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6663 // sequence to make it consistent
6664 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006665 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006666 mFocusedWindow->consumeMotionDown();
6667 // This cancel is generated because the connection was unresponsive
6668 mFocusedWindow->consumeMotionCancel();
6669 mFocusedWindow->assertNoEvents();
6670 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006671 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006672 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6673 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006674 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006675}
6676
6677// If we have 2 windows with identical timeouts that are both unresponsive,
6678// it doesn't matter which order they should have ANR.
6679// But we should receive ANR for both.
6680TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6681 // Set the timeout for unfocused window to match the focused window
6682 mUnfocusedWindow->setDispatchingTimeout(10ms);
6683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6684
6685 tapOnFocusedWindow();
6686 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006687 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6688 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6689 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006690
6691 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006692 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6693 mFocusedWindow->getToken() == anrConnectionToken2);
6694 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6695 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006696
6697 ASSERT_TRUE(mDispatcher->waitForIdle());
6698 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006699
6700 mFocusedWindow->consumeMotionDown();
6701 mFocusedWindow->consumeMotionUp();
6702 mUnfocusedWindow->consumeMotionOutside();
6703
Prabir Pradhanedd96402022-02-15 01:46:16 -08006704 sp<IBinder> responsiveToken1, responsiveToken2;
6705 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6706 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006707
6708 // Both applications should be marked as responsive, in any order
6709 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6710 mFocusedWindow->getToken() == responsiveToken2);
6711 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6712 mUnfocusedWindow->getToken() == responsiveToken2);
6713 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006714}
6715
6716// If a window is already not responding, the second tap on the same window should be ignored.
6717// We should also log an error to account for the dropped event (not tested here).
6718// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6719TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6720 tapOnFocusedWindow();
6721 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006722 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006723 // Receive the events, but don't respond
6724 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6725 ASSERT_TRUE(downEventSequenceNum);
6726 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6727 ASSERT_TRUE(upEventSequenceNum);
6728 const std::chrono::duration timeout =
6729 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006730 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006731
6732 // Tap once again
6733 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006734 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6736 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006738 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6739 FOCUSED_WINDOW_LOCATION));
6740 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6741 // valid touch target
6742 mUnfocusedWindow->assertNoEvents();
6743
6744 // Consume the first tap
6745 mFocusedWindow->finishEvent(*downEventSequenceNum);
6746 mFocusedWindow->finishEvent(*upEventSequenceNum);
6747 ASSERT_TRUE(mDispatcher->waitForIdle());
6748 // The second tap did not go to the focused window
6749 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006750 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006751 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6752 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006753 mFakePolicy->assertNotifyAnrWasNotCalled();
6754}
6755
6756// If you tap outside of all windows, there will not be ANR
6757TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006758 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006759 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6760 LOCATION_OUTSIDE_ALL_WINDOWS));
6761 ASSERT_TRUE(mDispatcher->waitForIdle());
6762 mFakePolicy->assertNotifyAnrWasNotCalled();
6763}
6764
6765// Since the focused window is paused, tapping on it should not produce any events
6766TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6767 mFocusedWindow->setPaused(true);
6768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6769
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006770 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006771 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6772 FOCUSED_WINDOW_LOCATION));
6773
6774 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6775 ASSERT_TRUE(mDispatcher->waitForIdle());
6776 // Should not ANR because the window is paused, and touches shouldn't go to it
6777 mFakePolicy->assertNotifyAnrWasNotCalled();
6778
6779 mFocusedWindow->assertNoEvents();
6780 mUnfocusedWindow->assertNoEvents();
6781}
6782
6783/**
6784 * If a window is processing a motion event, and then a key event comes in, the key event should
6785 * not to to the focused window until the motion is processed.
6786 * If a different window becomes focused at this time, the key should go to that window instead.
6787 *
6788 * Warning!!!
6789 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6790 * and the injection timeout that we specify when injecting the key.
6791 * We must have the injection timeout (10ms) be smaller than
6792 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6793 *
6794 * If that value changes, this test should also change.
6795 */
6796TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6797 // Set a long ANR timeout to prevent it from triggering
6798 mFocusedWindow->setDispatchingTimeout(2s);
6799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6800
6801 tapOnUnfocusedWindow();
6802 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6803 ASSERT_TRUE(downSequenceNum);
6804 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6805 ASSERT_TRUE(upSequenceNum);
6806 // Don't finish the events yet, and send a key
6807 // Injection will succeed because we will eventually give up and send the key to the focused
6808 // window even if motions are still being processed.
6809
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006810 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006811 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6812 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006814 // Key will not be sent to the window, yet, because the window is still processing events
6815 // and the key remains pending, waiting for the touch events to be processed
6816 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6817 ASSERT_FALSE(keySequenceNum);
6818
6819 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006820 mFocusedWindow->setFocusable(false);
6821 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006823 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006824
6825 // Focus events should precede the key events
6826 mUnfocusedWindow->consumeFocusEvent(true);
6827 mFocusedWindow->consumeFocusEvent(false);
6828
6829 // Finish the tap events, which should unblock dispatcher
6830 mUnfocusedWindow->finishEvent(*downSequenceNum);
6831 mUnfocusedWindow->finishEvent(*upSequenceNum);
6832
6833 // Now that all queues are cleared and no backlog in the connections, the key event
6834 // can finally go to the newly focused "mUnfocusedWindow".
6835 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6836 mFocusedWindow->assertNoEvents();
6837 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006838 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006839}
6840
6841// When the touch stream is split across 2 windows, and one of them does not respond,
6842// then ANR should be raised and the touch should be canceled for the unresponsive window.
6843// The other window should not be affected by that.
6844TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6845 // Touch Window 1
6846 NotifyMotionArgs motionArgs =
6847 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6848 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6849 mDispatcher->notifyMotion(&motionArgs);
6850 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006851 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006852
6853 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006854 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6855 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006856 mDispatcher->notifyMotion(&motionArgs);
6857
6858 const std::chrono::duration timeout =
6859 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006860 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006861
6862 mUnfocusedWindow->consumeMotionDown();
6863 mFocusedWindow->consumeMotionDown();
6864 // Focused window may or may not receive ACTION_MOVE
6865 // But it should definitely receive ACTION_CANCEL due to the ANR
6866 InputEvent* event;
6867 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6868 ASSERT_TRUE(moveOrCancelSequenceNum);
6869 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6870 ASSERT_NE(nullptr, event);
6871 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6872 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6873 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6874 mFocusedWindow->consumeMotionCancel();
6875 } else {
6876 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6877 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006878 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006879 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6880 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006881
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006882 mUnfocusedWindow->assertNoEvents();
6883 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006884 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006885}
6886
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006887/**
6888 * If we have no focused window, and a key comes in, we start the ANR timer.
6889 * The focused application should add a focused window before the timer runs out to prevent ANR.
6890 *
6891 * If the user touches another application during this time, the key should be dropped.
6892 * Next, if a new focused window comes in, without toggling the focused application,
6893 * then no ANR should occur.
6894 *
6895 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6896 * but in some cases the policy may not update the focused application.
6897 */
6898TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6899 std::shared_ptr<FakeApplicationHandle> focusedApplication =
6900 std::make_shared<FakeApplicationHandle>();
6901 focusedApplication->setDispatchingTimeout(60ms);
6902 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
6903 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
6904 mFocusedWindow->setFocusable(false);
6905
6906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6907 mFocusedWindow->consumeFocusEvent(false);
6908
6909 // Send a key. The ANR timer should start because there is no focused window.
6910 // 'focusedApplication' will get blamed if this timer completes.
6911 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006912 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006913 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6914 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6915 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006917
6918 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
6919 // then the injected touches won't cause the focused event to get dropped.
6920 // The dispatcher only checks for whether the queue should be pruned upon queueing.
6921 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
6922 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
6923 // For this test, it means that the key would get delivered to the window once it becomes
6924 // focused.
6925 std::this_thread::sleep_for(10ms);
6926
6927 // Touch unfocused window. This should force the pending key to get dropped.
6928 NotifyMotionArgs motionArgs =
6929 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6930 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
6931 mDispatcher->notifyMotion(&motionArgs);
6932
6933 // We do not consume the motion right away, because that would require dispatcher to first
6934 // process (== drop) the key event, and by that time, ANR will be raised.
6935 // Set the focused window first.
6936 mFocusedWindow->setFocusable(true);
6937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6938 setFocusedWindow(mFocusedWindow);
6939 mFocusedWindow->consumeFocusEvent(true);
6940 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
6941 // to another application. This could be a bug / behaviour in the policy.
6942
6943 mUnfocusedWindow->consumeMotionDown();
6944
6945 ASSERT_TRUE(mDispatcher->waitForIdle());
6946 // Should not ANR because we actually have a focused window. It was just added too slowly.
6947 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
6948}
6949
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006950// These tests ensure we cannot send touch events to a window that's positioned behind a window
6951// that has feature NO_INPUT_CHANNEL.
6952// Layout:
6953// Top (closest to user)
6954// mNoInputWindow (above all windows)
6955// mBottomWindow
6956// Bottom (furthest from user)
6957class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
6958 virtual void SetUp() override {
6959 InputDispatcherTest::SetUp();
6960
6961 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006962 mNoInputWindow =
6963 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6964 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00006965 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006966 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006967 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6968 // It's perfectly valid for this window to not have an associated input channel
6969
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006970 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
6971 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006972 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
6973
6974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6975 }
6976
6977protected:
6978 std::shared_ptr<FakeApplicationHandle> mApplication;
6979 sp<FakeWindowHandle> mNoInputWindow;
6980 sp<FakeWindowHandle> mBottomWindow;
6981};
6982
6983TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
6984 PointF touchedPoint = {10, 10};
6985
6986 NotifyMotionArgs motionArgs =
6987 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6988 ADISPLAY_ID_DEFAULT, {touchedPoint});
6989 mDispatcher->notifyMotion(&motionArgs);
6990
6991 mNoInputWindow->assertNoEvents();
6992 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
6993 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
6994 // and therefore should prevent mBottomWindow from receiving touches
6995 mBottomWindow->assertNoEvents();
6996}
6997
6998/**
6999 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
7000 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
7001 */
7002TEST_F(InputDispatcherMultiWindowOcclusionTests,
7003 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007004 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7005 "Window with input channel and NO_INPUT_CHANNEL",
7006 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007007
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007008 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007009 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7011
7012 PointF touchedPoint = {10, 10};
7013
7014 NotifyMotionArgs motionArgs =
7015 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7016 ADISPLAY_ID_DEFAULT, {touchedPoint});
7017 mDispatcher->notifyMotion(&motionArgs);
7018
7019 mNoInputWindow->assertNoEvents();
7020 mBottomWindow->assertNoEvents();
7021}
7022
Vishnu Nair958da932020-08-21 17:12:37 -07007023class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7024protected:
7025 std::shared_ptr<FakeApplicationHandle> mApp;
7026 sp<FakeWindowHandle> mWindow;
7027 sp<FakeWindowHandle> mMirror;
7028
7029 virtual void SetUp() override {
7030 InputDispatcherTest::SetUp();
7031 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007032 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7033 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7034 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007035 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7036 mWindow->setFocusable(true);
7037 mMirror->setFocusable(true);
7038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7039 }
7040};
7041
7042TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7043 // Request focus on a mirrored window
7044 setFocusedWindow(mMirror);
7045
7046 // window gets focused
7047 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7049 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007050 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7051}
7052
7053// A focused & mirrored window remains focused only if the window and its mirror are both
7054// focusable.
7055TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7056 setFocusedWindow(mMirror);
7057
7058 // window gets focused
7059 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7061 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007062 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7064 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007065 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7066
7067 mMirror->setFocusable(false);
7068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7069
7070 // window loses focus since one of the windows associated with the token in not focusable
7071 mWindow->consumeFocusEvent(false);
7072
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007073 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7074 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007075 mWindow->assertNoEvents();
7076}
7077
7078// A focused & mirrored window remains focused until the window and its mirror both become
7079// invisible.
7080TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7081 setFocusedWindow(mMirror);
7082
7083 // window gets focused
7084 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007085 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7086 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007087 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7089 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007090 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7091
7092 mMirror->setVisible(false);
7093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7094
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7096 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007097 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7099 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007100 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7101
7102 mWindow->setVisible(false);
7103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7104
7105 // window loses focus only after all windows associated with the token become invisible.
7106 mWindow->consumeFocusEvent(false);
7107
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007108 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7109 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007110 mWindow->assertNoEvents();
7111}
7112
7113// A focused & mirrored window remains focused until both windows are removed.
7114TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7115 setFocusedWindow(mMirror);
7116
7117 // window gets focused
7118 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7120 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007121 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7123 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007124 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7125
7126 // single window is removed but the window token remains focused
7127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7128
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007129 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7130 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007131 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7133 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007134 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7135
7136 // Both windows are removed
7137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7138 mWindow->consumeFocusEvent(false);
7139
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007140 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7141 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007142 mWindow->assertNoEvents();
7143}
7144
7145// Focus request can be pending until one window becomes visible.
7146TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7147 // Request focus on an invisible mirror.
7148 mWindow->setVisible(false);
7149 mMirror->setVisible(false);
7150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7151 setFocusedWindow(mMirror);
7152
7153 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007155 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7156 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007157
7158 mMirror->setVisible(true);
7159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7160
7161 // window gets focused
7162 mWindow->consumeFocusEvent(true);
7163 // window gets the pending key event
7164 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7165}
Prabir Pradhan99987712020-11-10 18:43:05 -08007166
7167class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7168protected:
7169 std::shared_ptr<FakeApplicationHandle> mApp;
7170 sp<FakeWindowHandle> mWindow;
7171 sp<FakeWindowHandle> mSecondWindow;
7172
7173 void SetUp() override {
7174 InputDispatcherTest::SetUp();
7175 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007176 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007177 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007178 mSecondWindow =
7179 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007180 mSecondWindow->setFocusable(true);
7181
7182 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7184
7185 setFocusedWindow(mWindow);
7186 mWindow->consumeFocusEvent(true);
7187 }
7188
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007189 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7190 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007191 mDispatcher->notifyPointerCaptureChanged(&args);
7192 }
7193
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007194 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7195 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007196 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007197 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7198 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007199 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007200 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007201 }
7202};
7203
7204TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7205 // Ensure that capture cannot be obtained for unfocused windows.
7206 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7207 mFakePolicy->assertSetPointerCaptureNotCalled();
7208 mSecondWindow->assertNoEvents();
7209
7210 // Ensure that capture can be enabled from the focus window.
7211 requestAndVerifyPointerCapture(mWindow, true);
7212
7213 // Ensure that capture cannot be disabled from a window that does not have capture.
7214 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7215 mFakePolicy->assertSetPointerCaptureNotCalled();
7216
7217 // Ensure that capture can be disabled from the window with capture.
7218 requestAndVerifyPointerCapture(mWindow, false);
7219}
7220
7221TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007222 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007223
7224 setFocusedWindow(mSecondWindow);
7225
7226 // Ensure that the capture disabled event was sent first.
7227 mWindow->consumeCaptureEvent(false);
7228 mWindow->consumeFocusEvent(false);
7229 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007230 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007231
7232 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007233 notifyPointerCaptureChanged({});
7234 notifyPointerCaptureChanged(request);
7235 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007236 mWindow->assertNoEvents();
7237 mSecondWindow->assertNoEvents();
7238 mFakePolicy->assertSetPointerCaptureNotCalled();
7239}
7240
7241TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007242 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007243
7244 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007245 notifyPointerCaptureChanged({});
7246 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007247
7248 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007249 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007250 mWindow->consumeCaptureEvent(false);
7251 mWindow->assertNoEvents();
7252}
7253
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007254TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7255 requestAndVerifyPointerCapture(mWindow, true);
7256
7257 // The first window loses focus.
7258 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007259 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007260 mWindow->consumeCaptureEvent(false);
7261
7262 // Request Pointer Capture from the second window before the notification from InputReader
7263 // arrives.
7264 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007265 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007266
7267 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007268 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007269
7270 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007271 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007272
7273 mSecondWindow->consumeFocusEvent(true);
7274 mSecondWindow->consumeCaptureEvent(true);
7275}
7276
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007277TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7278 // App repeatedly enables and disables capture.
7279 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7280 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7281 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7282 mFakePolicy->assertSetPointerCaptureCalled(false);
7283 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7284 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7285
7286 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7287 // first request is now stale, this should do nothing.
7288 notifyPointerCaptureChanged(firstRequest);
7289 mWindow->assertNoEvents();
7290
7291 // InputReader notifies that the second request was enabled.
7292 notifyPointerCaptureChanged(secondRequest);
7293 mWindow->consumeCaptureEvent(true);
7294}
7295
Prabir Pradhan7092e262022-05-03 16:51:09 +00007296TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7297 requestAndVerifyPointerCapture(mWindow, true);
7298
7299 // App toggles pointer capture off and on.
7300 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7301 mFakePolicy->assertSetPointerCaptureCalled(false);
7302
7303 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7304 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7305
7306 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7307 // preceding "disable" request.
7308 notifyPointerCaptureChanged(enableRequest);
7309
7310 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7311 // any notifications.
7312 mWindow->assertNoEvents();
7313}
7314
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007315class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7316protected:
7317 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007318
7319 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7320 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7321
7322 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7323 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7324
7325 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7326 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7327 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7328 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7329 MAXIMUM_OBSCURING_OPACITY);
7330
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007331 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007332 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007333 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007334
7335 sp<FakeWindowHandle> mTouchWindow;
7336
7337 virtual void SetUp() override {
7338 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007339 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007340 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7341 }
7342
7343 virtual void TearDown() override {
7344 InputDispatcherTest::TearDown();
7345 mTouchWindow.clear();
7346 }
7347
chaviw3277faf2021-05-19 16:45:23 -05007348 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7349 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007350 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007351 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007352 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007353 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007354 return window;
7355 }
7356
7357 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7358 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7359 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007360 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007361 // Generate an arbitrary PID based on the UID
7362 window->setOwnerInfo(1777 + (uid % 10000), uid);
7363 return window;
7364 }
7365
7366 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7367 NotifyMotionArgs args =
7368 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7369 ADISPLAY_ID_DEFAULT, points);
7370 mDispatcher->notifyMotion(&args);
7371 }
7372};
7373
7374TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007375 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007376 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007378
7379 touch();
7380
7381 mTouchWindow->assertNoEvents();
7382}
7383
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007384TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007385 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7386 const sp<FakeWindowHandle>& w =
7387 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7389
7390 touch();
7391
7392 mTouchWindow->assertNoEvents();
7393}
7394
7395TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007396 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7397 const sp<FakeWindowHandle>& w =
7398 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7400
7401 touch();
7402
7403 w->assertNoEvents();
7404}
7405
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007406TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007407 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007409
7410 touch();
7411
7412 mTouchWindow->consumeAnyMotionDown();
7413}
7414
7415TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007416 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007417 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007418 w->setFrame(Rect(0, 0, 50, 50));
7419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007420
7421 touch({PointF{100, 100}});
7422
7423 mTouchWindow->consumeAnyMotionDown();
7424}
7425
7426TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007427 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007428 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7430
7431 touch();
7432
7433 mTouchWindow->consumeAnyMotionDown();
7434}
7435
7436TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7437 const sp<FakeWindowHandle>& w =
7438 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007440
7441 touch();
7442
7443 mTouchWindow->consumeAnyMotionDown();
7444}
7445
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007446TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7447 const sp<FakeWindowHandle>& w =
7448 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7449 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7450
7451 touch();
7452
7453 w->assertNoEvents();
7454}
7455
7456/**
7457 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7458 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7459 * window, the occluding window will still receive ACTION_OUTSIDE event.
7460 */
7461TEST_F(InputDispatcherUntrustedTouchesTest,
7462 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7463 const sp<FakeWindowHandle>& w =
7464 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007465 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7467
7468 touch();
7469
7470 w->consumeMotionOutside();
7471}
7472
7473TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7474 const sp<FakeWindowHandle>& w =
7475 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007476 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7478
7479 touch();
7480
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007481 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007482}
7483
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007484TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007485 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007486 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7487 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7489
7490 touch();
7491
7492 mTouchWindow->consumeAnyMotionDown();
7493}
7494
7495TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7496 const sp<FakeWindowHandle>& w =
7497 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7498 MAXIMUM_OBSCURING_OPACITY);
7499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007500
7501 touch();
7502
7503 mTouchWindow->consumeAnyMotionDown();
7504}
7505
7506TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007507 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007508 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7509 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7511
7512 touch();
7513
7514 mTouchWindow->assertNoEvents();
7515}
7516
7517TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7518 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7519 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007520 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7521 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007522 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007523 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7524 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7526
7527 touch();
7528
7529 mTouchWindow->assertNoEvents();
7530}
7531
7532TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7533 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7534 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007535 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7536 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007537 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007538 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7539 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7541
7542 touch();
7543
7544 mTouchWindow->consumeAnyMotionDown();
7545}
7546
7547TEST_F(InputDispatcherUntrustedTouchesTest,
7548 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7549 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007550 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7551 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007552 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007553 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7554 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7556
7557 touch();
7558
7559 mTouchWindow->consumeAnyMotionDown();
7560}
7561
7562TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7563 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007564 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7565 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007566 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007567 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7568 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007570
7571 touch();
7572
7573 mTouchWindow->assertNoEvents();
7574}
7575
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007576TEST_F(InputDispatcherUntrustedTouchesTest,
7577 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7578 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007579 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7580 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007581 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007582 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7583 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7585
7586 touch();
7587
7588 mTouchWindow->assertNoEvents();
7589}
7590
7591TEST_F(InputDispatcherUntrustedTouchesTest,
7592 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7593 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007594 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7595 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007596 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007597 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7598 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7600
7601 touch();
7602
7603 mTouchWindow->consumeAnyMotionDown();
7604}
7605
7606TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7607 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007608 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7609 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7611
7612 touch();
7613
7614 mTouchWindow->consumeAnyMotionDown();
7615}
7616
7617TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7618 const sp<FakeWindowHandle>& w =
7619 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7621
7622 touch();
7623
7624 mTouchWindow->consumeAnyMotionDown();
7625}
7626
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007627TEST_F(InputDispatcherUntrustedTouchesTest,
7628 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7629 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7630 const sp<FakeWindowHandle>& w =
7631 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7633
7634 touch();
7635
7636 mTouchWindow->assertNoEvents();
7637}
7638
7639TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7640 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7641 const sp<FakeWindowHandle>& w =
7642 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7644
7645 touch();
7646
7647 mTouchWindow->consumeAnyMotionDown();
7648}
7649
7650TEST_F(InputDispatcherUntrustedTouchesTest,
7651 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7652 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7653 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007654 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7655 OPACITY_ABOVE_THRESHOLD);
7656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7657
7658 touch();
7659
7660 mTouchWindow->consumeAnyMotionDown();
7661}
7662
7663TEST_F(InputDispatcherUntrustedTouchesTest,
7664 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7665 const sp<FakeWindowHandle>& w1 =
7666 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7667 OPACITY_BELOW_THRESHOLD);
7668 const sp<FakeWindowHandle>& w2 =
7669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7670 OPACITY_BELOW_THRESHOLD);
7671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7672
7673 touch();
7674
7675 mTouchWindow->assertNoEvents();
7676}
7677
7678/**
7679 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7680 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7681 * (which alone would result in allowing touches) does not affect the blocking behavior.
7682 */
7683TEST_F(InputDispatcherUntrustedTouchesTest,
7684 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7685 const sp<FakeWindowHandle>& wB =
7686 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7687 OPACITY_BELOW_THRESHOLD);
7688 const sp<FakeWindowHandle>& wC =
7689 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7690 OPACITY_BELOW_THRESHOLD);
7691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7692
7693 touch();
7694
7695 mTouchWindow->assertNoEvents();
7696}
7697
7698/**
7699 * This test is testing that a window from a different UID but with same application token doesn't
7700 * block the touch. Apps can share the application token for close UI collaboration for example.
7701 */
7702TEST_F(InputDispatcherUntrustedTouchesTest,
7703 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7704 const sp<FakeWindowHandle>& w =
7705 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7706 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7708
7709 touch();
7710
7711 mTouchWindow->consumeAnyMotionDown();
7712}
7713
arthurhungb89ccb02020-12-30 16:19:01 +08007714class InputDispatcherDragTests : public InputDispatcherTest {
7715protected:
7716 std::shared_ptr<FakeApplicationHandle> mApp;
7717 sp<FakeWindowHandle> mWindow;
7718 sp<FakeWindowHandle> mSecondWindow;
7719 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007720 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007721 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7722 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007723
7724 void SetUp() override {
7725 InputDispatcherTest::SetUp();
7726 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007727 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007728 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007729
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007730 mSecondWindow =
7731 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007732 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007733
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007734 mSpyWindow =
7735 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007736 mSpyWindow->setSpy(true);
7737 mSpyWindow->setTrustedOverlay(true);
7738 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7739
arthurhungb89ccb02020-12-30 16:19:01 +08007740 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007742 }
7743
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007744 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7745 switch (fromSource) {
7746 case AINPUT_SOURCE_TOUCHSCREEN:
7747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7748 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7749 ADISPLAY_ID_DEFAULT, {50, 50}))
7750 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7751 break;
7752 case AINPUT_SOURCE_STYLUS:
7753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7754 injectMotionEvent(
7755 mDispatcher,
7756 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7757 AINPUT_SOURCE_STYLUS)
7758 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7759 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7760 .x(50)
7761 .y(50))
7762 .build()));
7763 break;
7764 case AINPUT_SOURCE_MOUSE:
7765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7766 injectMotionEvent(
7767 mDispatcher,
7768 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7769 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7770 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7771 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7772 .x(50)
7773 .y(50))
7774 .build()));
7775 break;
7776 default:
7777 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7778 }
arthurhungb89ccb02020-12-30 16:19:01 +08007779
7780 // Window should receive motion event.
7781 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007782 // Spy window should also receive motion event
7783 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007784 }
7785
7786 // Start performing drag, we will create a drag window and transfer touch to it.
7787 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7788 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007789 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007790 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007791 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007792 }
arthurhungb89ccb02020-12-30 16:19:01 +08007793
7794 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007795 mDragWindow =
7796 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007797 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007798 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007799 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007800
7801 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007802 bool transferred =
7803 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007804 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007805 if (transferred) {
7806 mWindow->consumeMotionCancel();
7807 mDragWindow->consumeMotionDown();
7808 }
7809 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007810 }
7811};
7812
7813TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007814 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007815
7816 // Move on window.
7817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7818 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7819 ADISPLAY_ID_DEFAULT, {50, 50}))
7820 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7821 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7822 mWindow->consumeDragEvent(false, 50, 50);
7823 mSecondWindow->assertNoEvents();
7824
7825 // Move to another window.
7826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7827 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7828 ADISPLAY_ID_DEFAULT, {150, 50}))
7829 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7830 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7831 mWindow->consumeDragEvent(true, 150, 50);
7832 mSecondWindow->consumeDragEvent(false, 50, 50);
7833
7834 // Move back to original window.
7835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7836 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7837 ADISPLAY_ID_DEFAULT, {50, 50}))
7838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7839 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7840 mWindow->consumeDragEvent(false, 50, 50);
7841 mSecondWindow->consumeDragEvent(true, -50, 50);
7842
7843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7844 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7845 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7846 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7847 mWindow->assertNoEvents();
7848 mSecondWindow->assertNoEvents();
7849}
7850
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007851TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007852 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007853
7854 // No cancel event after drag start
7855 mSpyWindow->assertNoEvents();
7856
7857 const MotionEvent secondFingerDownEvent =
7858 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7859 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007860 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7861 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007862 .build();
7863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7864 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7865 InputEventInjectionSync::WAIT_FOR_RESULT))
7866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7867
7868 // Receives cancel for first pointer after next pointer down
7869 mSpyWindow->consumeMotionCancel();
7870 mSpyWindow->consumeMotionDown();
7871
7872 mSpyWindow->assertNoEvents();
7873}
7874
arthurhungf452d0b2021-01-06 00:19:52 +08007875TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007876 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007877
7878 // Move on window.
7879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7880 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7881 ADISPLAY_ID_DEFAULT, {50, 50}))
7882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7883 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7884 mWindow->consumeDragEvent(false, 50, 50);
7885 mSecondWindow->assertNoEvents();
7886
7887 // Move to another window.
7888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7889 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7890 ADISPLAY_ID_DEFAULT, {150, 50}))
7891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7892 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7893 mWindow->consumeDragEvent(true, 150, 50);
7894 mSecondWindow->consumeDragEvent(false, 50, 50);
7895
7896 // drop to another window.
7897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7898 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7899 {150, 50}))
7900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7901 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7902 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7903 mWindow->assertNoEvents();
7904 mSecondWindow->assertNoEvents();
7905}
7906
arthurhung6d4bed92021-03-17 11:59:33 +08007907TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007908 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08007909
7910 // Move on window and keep button pressed.
7911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7912 injectMotionEvent(mDispatcher,
7913 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7914 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7915 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7916 .x(50)
7917 .y(50))
7918 .build()))
7919 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7920 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7921 mWindow->consumeDragEvent(false, 50, 50);
7922 mSecondWindow->assertNoEvents();
7923
7924 // Move to another window and release button, expect to drop item.
7925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7926 injectMotionEvent(mDispatcher,
7927 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7928 .buttonState(0)
7929 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7930 .x(150)
7931 .y(50))
7932 .build()))
7933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7934 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7935 mWindow->assertNoEvents();
7936 mSecondWindow->assertNoEvents();
7937 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7938
7939 // nothing to the window.
7940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7941 injectMotionEvent(mDispatcher,
7942 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
7943 .buttonState(0)
7944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7945 .x(150)
7946 .y(50))
7947 .build()))
7948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7949 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7950 mWindow->assertNoEvents();
7951 mSecondWindow->assertNoEvents();
7952}
7953
Arthur Hung54745652022-04-20 07:17:41 +00007954TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007955 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08007956
7957 // Set second window invisible.
7958 mSecondWindow->setVisible(false);
7959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
7960
7961 // Move on window.
7962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7963 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7964 ADISPLAY_ID_DEFAULT, {50, 50}))
7965 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7966 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7967 mWindow->consumeDragEvent(false, 50, 50);
7968 mSecondWindow->assertNoEvents();
7969
7970 // Move to another window.
7971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7972 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7973 ADISPLAY_ID_DEFAULT, {150, 50}))
7974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7975 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7976 mWindow->consumeDragEvent(true, 150, 50);
7977 mSecondWindow->assertNoEvents();
7978
7979 // drop to another window.
7980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7981 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7982 {150, 50}))
7983 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7984 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7985 mFakePolicy->assertDropTargetEquals(nullptr);
7986 mWindow->assertNoEvents();
7987 mSecondWindow->assertNoEvents();
7988}
7989
Arthur Hung54745652022-04-20 07:17:41 +00007990TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007991 // Ensure window could track pointerIds if it didn't support split touch.
7992 mWindow->setPreventSplitting(true);
7993
Arthur Hung54745652022-04-20 07:17:41 +00007994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7995 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7996 {50, 50}))
7997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7998 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7999
8000 const MotionEvent secondFingerDownEvent =
8001 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8002 .displayId(ADISPLAY_ID_DEFAULT)
8003 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008004 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8005 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008006 .build();
8007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8008 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8009 InputEventInjectionSync::WAIT_FOR_RESULT))
8010 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008011 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00008012
8013 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008014 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008015}
8016
8017TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
8018 // First down on second window.
8019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8020 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8021 {150, 50}))
8022 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8023
8024 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8025
8026 // Second down on first window.
8027 const MotionEvent secondFingerDownEvent =
8028 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8029 .displayId(ADISPLAY_ID_DEFAULT)
8030 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008031 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8032 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008033 .build();
8034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8035 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8036 InputEventInjectionSync::WAIT_FOR_RESULT))
8037 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8038 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8039
8040 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008041 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008042
8043 // Move on window.
8044 const MotionEvent secondFingerMoveEvent =
8045 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8046 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008047 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8048 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008049 .build();
8050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8051 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8052 InputEventInjectionSync::WAIT_FOR_RESULT));
8053 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8054 mWindow->consumeDragEvent(false, 50, 50);
8055 mSecondWindow->consumeMotionMove();
8056
8057 // Release the drag pointer should perform drop.
8058 const MotionEvent secondFingerUpEvent =
8059 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8060 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008061 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8062 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008063 .build();
8064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8065 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8066 InputEventInjectionSync::WAIT_FOR_RESULT));
8067 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8068 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8069 mWindow->assertNoEvents();
8070 mSecondWindow->consumeMotionMove();
8071}
8072
Arthur Hung3915c1f2022-05-31 07:17:17 +00008073TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008074 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008075
8076 // Update window of second display.
8077 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008078 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008079 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8080
8081 // Let second display has a touch state.
8082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8083 injectMotionEvent(mDispatcher,
8084 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8085 AINPUT_SOURCE_TOUCHSCREEN)
8086 .displayId(SECOND_DISPLAY_ID)
8087 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8088 .x(100)
8089 .y(100))
8090 .build()));
8091 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008092 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008093 // Update window again.
8094 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8095
8096 // Move on window.
8097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8098 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8099 ADISPLAY_ID_DEFAULT, {50, 50}))
8100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8101 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8102 mWindow->consumeDragEvent(false, 50, 50);
8103 mSecondWindow->assertNoEvents();
8104
8105 // Move to another window.
8106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8107 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8108 ADISPLAY_ID_DEFAULT, {150, 50}))
8109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8110 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8111 mWindow->consumeDragEvent(true, 150, 50);
8112 mSecondWindow->consumeDragEvent(false, 50, 50);
8113
8114 // drop to another window.
8115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8116 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8117 {150, 50}))
8118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8119 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8120 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8121 mWindow->assertNoEvents();
8122 mSecondWindow->assertNoEvents();
8123}
8124
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008125TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8126 startDrag(true, AINPUT_SOURCE_MOUSE);
8127 // Move on window.
8128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8129 injectMotionEvent(mDispatcher,
8130 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8131 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8132 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8133 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8134 .x(50)
8135 .y(50))
8136 .build()))
8137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8138 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8139 mWindow->consumeDragEvent(false, 50, 50);
8140 mSecondWindow->assertNoEvents();
8141
8142 // Move to another window.
8143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8144 injectMotionEvent(mDispatcher,
8145 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8146 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8147 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8148 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8149 .x(150)
8150 .y(50))
8151 .build()))
8152 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8153 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8154 mWindow->consumeDragEvent(true, 150, 50);
8155 mSecondWindow->consumeDragEvent(false, 50, 50);
8156
8157 // drop to another window.
8158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8159 injectMotionEvent(mDispatcher,
8160 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8161 .buttonState(0)
8162 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8163 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8164 .x(150)
8165 .y(50))
8166 .build()))
8167 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8168 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8169 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8170 mWindow->assertNoEvents();
8171 mSecondWindow->assertNoEvents();
8172}
8173
Vishnu Nair062a8672021-09-03 16:07:44 -07008174class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8175
8176TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8177 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008178 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8179 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008180 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008181 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8182 window->setFocusable(true);
8183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8184 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008185 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008186
8187 // With the flag set, window should not get any input
8188 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8189 mDispatcher->notifyKey(&keyArgs);
8190 window->assertNoEvents();
8191
8192 NotifyMotionArgs motionArgs =
8193 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8194 ADISPLAY_ID_DEFAULT);
8195 mDispatcher->notifyMotion(&motionArgs);
8196 window->assertNoEvents();
8197
8198 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008199 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8201
8202 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8203 mDispatcher->notifyKey(&keyArgs);
8204 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8205
8206 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8207 ADISPLAY_ID_DEFAULT);
8208 mDispatcher->notifyMotion(&motionArgs);
8209 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8210 window->assertNoEvents();
8211}
8212
8213TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8214 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8215 std::make_shared<FakeApplicationHandle>();
8216 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008217 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8218 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008219 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8220 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008221 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008222 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008223 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8224 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008225 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008226 window->setOwnerInfo(222, 222);
8227 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8228 window->setFocusable(true);
8229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8230 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008231 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008232
8233 // With the flag set, window should not get any input
8234 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8235 mDispatcher->notifyKey(&keyArgs);
8236 window->assertNoEvents();
8237
8238 NotifyMotionArgs motionArgs =
8239 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8240 ADISPLAY_ID_DEFAULT);
8241 mDispatcher->notifyMotion(&motionArgs);
8242 window->assertNoEvents();
8243
8244 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008245 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008246 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8247
8248 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8249 mDispatcher->notifyKey(&keyArgs);
8250 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8251
8252 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8253 ADISPLAY_ID_DEFAULT);
8254 mDispatcher->notifyMotion(&motionArgs);
8255 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8256 window->assertNoEvents();
8257}
8258
8259TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8260 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8261 std::make_shared<FakeApplicationHandle>();
8262 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008263 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8264 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008265 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8266 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008267 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008268 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008269 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8270 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008271 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008272 window->setOwnerInfo(222, 222);
8273 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8274 window->setFocusable(true);
8275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8276 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008277 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008278
8279 // With the flag set, window should not get any input
8280 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8281 mDispatcher->notifyKey(&keyArgs);
8282 window->assertNoEvents();
8283
8284 NotifyMotionArgs motionArgs =
8285 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8286 ADISPLAY_ID_DEFAULT);
8287 mDispatcher->notifyMotion(&motionArgs);
8288 window->assertNoEvents();
8289
8290 // When the window is no longer obscured because it went on top, it should get input
8291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8292
8293 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8294 mDispatcher->notifyKey(&keyArgs);
8295 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8296
8297 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8298 ADISPLAY_ID_DEFAULT);
8299 mDispatcher->notifyMotion(&motionArgs);
8300 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8301 window->assertNoEvents();
8302}
8303
Antonio Kantekf16f2832021-09-28 04:39:20 +00008304class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8305protected:
8306 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008307 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008308 sp<FakeWindowHandle> mWindow;
8309 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008310 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008311
8312 void SetUp() override {
8313 InputDispatcherTest::SetUp();
8314
8315 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008316 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008317 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008318 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008319 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008320 mSecondWindow =
8321 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008322 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008323 mThirdWindow =
8324 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8325 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8326 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008327
8328 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8330 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8331 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008332 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008333
Antonio Kantek15beb512022-06-13 22:35:41 +00008334 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008335 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008336 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008337 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8338 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008339 mThirdWindow->assertNoEvents();
8340 }
8341
8342 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8343 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008344 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008345 SECOND_DISPLAY_ID)) {
8346 mWindow->assertNoEvents();
8347 mSecondWindow->assertNoEvents();
8348 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008349 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008350 }
8351
Antonio Kantek15beb512022-06-13 22:35:41 +00008352 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8353 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008354 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8355 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008356 mWindow->consumeTouchModeEvent(inTouchMode);
8357 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008358 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008359 }
8360};
8361
Antonio Kantek26defcf2022-02-08 01:12:27 +00008362TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008363 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008364 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8365 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008366 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008367}
8368
Antonio Kantek26defcf2022-02-08 01:12:27 +00008369TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8370 const WindowInfo& windowInfo = *mWindow->getInfo();
8371 int32_t ownerPid = windowInfo.ownerPid;
8372 int32_t ownerUid = windowInfo.ownerUid;
8373 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8374 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008375 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008376 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008377 mWindow->assertNoEvents();
8378 mSecondWindow->assertNoEvents();
8379}
8380
8381TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8382 const WindowInfo& windowInfo = *mWindow->getInfo();
8383 int32_t ownerPid = windowInfo.ownerPid;
8384 int32_t ownerUid = windowInfo.ownerUid;
8385 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008386 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008387 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008388}
8389
Antonio Kantekf16f2832021-09-28 04:39:20 +00008390TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008391 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008392 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8393 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008394 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008395 mWindow->assertNoEvents();
8396 mSecondWindow->assertNoEvents();
8397}
8398
Antonio Kantek15beb512022-06-13 22:35:41 +00008399TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8400 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8401 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8402 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008403 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008404 mWindow->assertNoEvents();
8405 mSecondWindow->assertNoEvents();
8406 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8407}
8408
Antonio Kantek48710e42022-03-24 14:19:30 -07008409TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8410 // Interact with the window first.
8411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8412 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8413 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8414
8415 // Then remove focus.
8416 mWindow->setFocusable(false);
8417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8418
8419 // Assert that caller can switch touch mode by owning one of the last interacted window.
8420 const WindowInfo& windowInfo = *mWindow->getInfo();
8421 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8422 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008423 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008424}
8425
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008426class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8427public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008428 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008429 std::shared_ptr<FakeApplicationHandle> application =
8430 std::make_shared<FakeApplicationHandle>();
8431 std::string name = "Fake Spy ";
8432 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008433 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8434 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008435 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008436 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008437 return spy;
8438 }
8439
8440 sp<FakeWindowHandle> createForeground() {
8441 std::shared_ptr<FakeApplicationHandle> application =
8442 std::make_shared<FakeApplicationHandle>();
8443 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008444 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8445 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008446 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008447 return window;
8448 }
8449
8450private:
8451 int mSpyCount{0};
8452};
8453
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008454using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008455/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008456 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8457 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008458TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8459 ScopedSilentDeath _silentDeath;
8460
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008461 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008462 spy->setTrustedOverlay(false);
8463 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8464 ".* not a trusted overlay");
8465}
8466
8467/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008468 * Input injection into a display with a spy window but no foreground windows should succeed.
8469 */
8470TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008471 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8473
8474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8475 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8476 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8477 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8478}
8479
8480/**
8481 * Verify the order in which different input windows receive events. The touched foreground window
8482 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8483 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8484 * receive events before ones belows it.
8485 *
8486 * Here, we set up a scenario with four windows in the following Z order from the top:
8487 * spy1, spy2, window, spy3.
8488 * We then inject an event and verify that the foreground "window" receives it first, followed by
8489 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8490 * window.
8491 */
8492TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8493 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008494 auto spy1 = createSpy();
8495 auto spy2 = createSpy();
8496 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8498 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8499 const size_t numChannels = channels.size();
8500
Michael Wright8e9a8562022-02-09 13:44:29 +00008501 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008502 if (!epollFd.ok()) {
8503 FAIL() << "Failed to create epoll fd";
8504 }
8505
8506 for (size_t i = 0; i < numChannels; i++) {
8507 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8508 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8509 FAIL() << "Failed to add fd to epoll";
8510 }
8511 }
8512
8513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8514 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8515 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8516
8517 std::vector<size_t> eventOrder;
8518 std::vector<struct epoll_event> events(numChannels);
8519 for (;;) {
8520 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8521 (100ms).count());
8522 if (nFds < 0) {
8523 FAIL() << "Failed to call epoll_wait";
8524 }
8525 if (nFds == 0) {
8526 break; // epoll_wait timed out
8527 }
8528 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008529 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008530 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008531 channels[i]->consumeMotionDown();
8532 }
8533 }
8534
8535 // Verify the order in which the events were received.
8536 EXPECT_EQ(3u, eventOrder.size());
8537 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8538 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8539 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8540}
8541
8542/**
8543 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8544 */
8545TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8546 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008547 auto spy = createSpy();
8548 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8550
8551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8552 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8553 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8554 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8555 spy->assertNoEvents();
8556}
8557
8558/**
8559 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8560 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8561 * to the window.
8562 */
8563TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8564 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008565 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008566 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8568
8569 // Inject an event outside the spy window's touchable region.
8570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8571 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8572 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8573 window->consumeMotionDown();
8574 spy->assertNoEvents();
8575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8576 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8578 window->consumeMotionUp();
8579 spy->assertNoEvents();
8580
8581 // Inject an event inside the spy window's touchable region.
8582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8584 {5, 10}))
8585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8586 window->consumeMotionDown();
8587 spy->consumeMotionDown();
8588}
8589
8590/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008591 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008592 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008593 */
8594TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8595 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008596 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008597 auto spy = createSpy();
8598 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008599 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008600 spy->setFrame(Rect{0, 0, 20, 20});
8601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8602
8603 // Inject an event outside the spy window's frame and touchable region.
8604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008605 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8606 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8608 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008609 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008610}
8611
8612/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008613 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8614 * pointers that are down within its bounds.
8615 */
8616TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8617 auto windowLeft = createForeground();
8618 windowLeft->setFrame({0, 0, 100, 200});
8619 auto windowRight = createForeground();
8620 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008621 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008622 spy->setFrame({0, 0, 200, 200});
8623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8624
8625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8626 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8627 {50, 50}))
8628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8629 windowLeft->consumeMotionDown();
8630 spy->consumeMotionDown();
8631
8632 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008633 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008634 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008635 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8636 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008637 .build();
8638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8639 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8640 InputEventInjectionSync::WAIT_FOR_RESULT))
8641 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8642 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008643 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008644}
8645
8646/**
8647 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8648 * the spy should receive the second pointer with ACTION_DOWN.
8649 */
8650TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8651 auto window = createForeground();
8652 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008653 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008654 spyRight->setFrame({100, 0, 200, 200});
8655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8656
8657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8659 {50, 50}))
8660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8661 window->consumeMotionDown();
8662 spyRight->assertNoEvents();
8663
8664 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008665 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008666 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008667 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8668 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008669 .build();
8670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8671 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8672 InputEventInjectionSync::WAIT_FOR_RESULT))
8673 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008674 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008675 spyRight->consumeMotionDown();
8676}
8677
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008678/**
8679 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8680 * windows should be allowed to control split touch.
8681 */
8682TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008683 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008684 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008685 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008686 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008687
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008688 auto window = createForeground();
8689 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008690
8691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8692
8693 // First finger down, no window touched.
8694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8695 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8696 {100, 200}))
8697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8698 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8699 window->assertNoEvents();
8700
8701 // Second finger down on window, the window should receive touch down.
8702 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008703 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008704 .displayId(ADISPLAY_ID_DEFAULT)
8705 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008706 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8707 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008708 .build();
8709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8710 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8711 InputEventInjectionSync::WAIT_FOR_RESULT))
8712 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8713
8714 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008715 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008716}
8717
8718/**
8719 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8720 * do not receive key events.
8721 */
8722TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008723 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008724 spy->setFocusable(false);
8725
8726 auto window = createForeground();
8727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8728 setFocusedWindow(window);
8729 window->consumeFocusEvent(true);
8730
8731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8732 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8733 window->consumeKeyDown(ADISPLAY_ID_NONE);
8734
8735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8736 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8737 window->consumeKeyUp(ADISPLAY_ID_NONE);
8738
8739 spy->assertNoEvents();
8740}
8741
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008742using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8743
8744/**
8745 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8746 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8747 */
8748TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8749 auto window = createForeground();
8750 auto spy1 = createSpy();
8751 auto spy2 = createSpy();
8752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8753
8754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8755 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8756 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8757 window->consumeMotionDown();
8758 spy1->consumeMotionDown();
8759 spy2->consumeMotionDown();
8760
8761 // Pilfer pointers from the second spy window.
8762 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8763 spy2->assertNoEvents();
8764 spy1->consumeMotionCancel();
8765 window->consumeMotionCancel();
8766
8767 // The rest of the gesture should only be sent to the second spy window.
8768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8769 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8770 ADISPLAY_ID_DEFAULT))
8771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8772 spy2->consumeMotionMove();
8773 spy1->assertNoEvents();
8774 window->assertNoEvents();
8775}
8776
8777/**
8778 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8779 * in the middle of the gesture.
8780 */
8781TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8782 auto window = createForeground();
8783 auto spy = createSpy();
8784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8785
8786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8787 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8789 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8790 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8791
8792 window->releaseChannel();
8793
8794 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8795
8796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8797 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8798 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8799 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8800}
8801
8802/**
8803 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8804 * the spy, but not to any other windows.
8805 */
8806TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8807 auto spy = createSpy();
8808 auto window = createForeground();
8809
8810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8811
8812 // First finger down on the window and the spy.
8813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8814 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8815 {100, 200}))
8816 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8817 spy->consumeMotionDown();
8818 window->consumeMotionDown();
8819
8820 // Spy window pilfers the pointers.
8821 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8822 window->consumeMotionCancel();
8823
8824 // Second finger down on the window and spy, but the window should not receive the pointer down.
8825 const MotionEvent secondFingerDownEvent =
8826 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8827 .displayId(ADISPLAY_ID_DEFAULT)
8828 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008829 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8830 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008831 .build();
8832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8833 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8834 InputEventInjectionSync::WAIT_FOR_RESULT))
8835 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8836
Harry Cutts33476232023-01-30 19:57:29 +00008837 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008838
8839 // Third finger goes down outside all windows, so injection should fail.
8840 const MotionEvent thirdFingerDownEvent =
8841 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8842 .displayId(ADISPLAY_ID_DEFAULT)
8843 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008844 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8845 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8846 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008847 .build();
8848 ASSERT_EQ(InputEventInjectionResult::FAILED,
8849 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8850 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008851 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008852
8853 spy->assertNoEvents();
8854 window->assertNoEvents();
8855}
8856
8857/**
8858 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8859 */
8860TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8861 auto spy = createSpy();
8862 spy->setFrame(Rect(0, 0, 100, 100));
8863 auto window = createForeground();
8864 window->setFrame(Rect(0, 0, 200, 200));
8865
8866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8867
8868 // First finger down on the window only
8869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8870 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8871 {150, 150}))
8872 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8873 window->consumeMotionDown();
8874
8875 // Second finger down on the spy and window
8876 const MotionEvent secondFingerDownEvent =
8877 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8878 .displayId(ADISPLAY_ID_DEFAULT)
8879 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008880 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8881 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008882 .build();
8883 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8884 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8885 InputEventInjectionSync::WAIT_FOR_RESULT))
8886 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8887 spy->consumeMotionDown();
8888 window->consumeMotionPointerDown(1);
8889
8890 // Third finger down on the spy and window
8891 const MotionEvent thirdFingerDownEvent =
8892 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8893 .displayId(ADISPLAY_ID_DEFAULT)
8894 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008895 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8896 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8897 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008898 .build();
8899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8900 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8901 InputEventInjectionSync::WAIT_FOR_RESULT))
8902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8903 spy->consumeMotionPointerDown(1);
8904 window->consumeMotionPointerDown(2);
8905
8906 // Spy window pilfers the pointers.
8907 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8908 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8909 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8910
8911 spy->assertNoEvents();
8912 window->assertNoEvents();
8913}
8914
8915/**
8916 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
8917 * other windows should be canceled. If this results in the cancellation of all pointers for some
8918 * window, then that window should receive ACTION_CANCEL.
8919 */
8920TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
8921 auto spy = createSpy();
8922 spy->setFrame(Rect(0, 0, 100, 100));
8923 auto window = createForeground();
8924 window->setFrame(Rect(0, 0, 200, 200));
8925
8926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8927
8928 // First finger down on both spy and window
8929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8930 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8931 {10, 10}))
8932 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8933 window->consumeMotionDown();
8934 spy->consumeMotionDown();
8935
8936 // Second finger down on the spy and window
8937 const MotionEvent secondFingerDownEvent =
8938 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8939 .displayId(ADISPLAY_ID_DEFAULT)
8940 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008941 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8942 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008943 .build();
8944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8945 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8946 InputEventInjectionSync::WAIT_FOR_RESULT))
8947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8948 spy->consumeMotionPointerDown(1);
8949 window->consumeMotionPointerDown(1);
8950
8951 // Spy window pilfers the pointers.
8952 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8953 window->consumeMotionCancel();
8954
8955 spy->assertNoEvents();
8956 window->assertNoEvents();
8957}
8958
8959/**
8960 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
8961 * be sent to other windows
8962 */
8963TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
8964 auto spy = createSpy();
8965 spy->setFrame(Rect(0, 0, 100, 100));
8966 auto window = createForeground();
8967 window->setFrame(Rect(0, 0, 200, 200));
8968
8969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8970
8971 // First finger down on both window and spy
8972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8973 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8974 {10, 10}))
8975 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8976 window->consumeMotionDown();
8977 spy->consumeMotionDown();
8978
8979 // Spy window pilfers the pointers.
8980 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8981 window->consumeMotionCancel();
8982
8983 // Second finger down on the window only
8984 const MotionEvent secondFingerDownEvent =
8985 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8986 .displayId(ADISPLAY_ID_DEFAULT)
8987 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008988 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8989 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008990 .build();
8991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8992 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8993 InputEventInjectionSync::WAIT_FOR_RESULT))
8994 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8995 window->consumeMotionDown();
8996 window->assertNoEvents();
8997
8998 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
8999 spy->consumeMotionMove();
9000 spy->assertNoEvents();
9001}
9002
Prabir Pradhand65552b2021-10-07 11:23:50 -07009003class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
9004public:
9005 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
9006 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9007 std::make_shared<FakeApplicationHandle>();
9008 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009009 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
9010 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009011 overlay->setFocusable(false);
9012 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08009013 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009014 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009015 overlay->setTrustedOverlay(true);
9016
9017 std::shared_ptr<FakeApplicationHandle> application =
9018 std::make_shared<FakeApplicationHandle>();
9019 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009020 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9021 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009022 window->setFocusable(true);
9023 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009024
9025 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9027 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009028 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009029 return {std::move(overlay), std::move(window)};
9030 }
9031
9032 void sendFingerEvent(int32_t action) {
9033 NotifyMotionArgs motionArgs =
9034 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9035 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9036 mDispatcher->notifyMotion(&motionArgs);
9037 }
9038
9039 void sendStylusEvent(int32_t action) {
9040 NotifyMotionArgs motionArgs =
9041 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9042 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9043 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9044 mDispatcher->notifyMotion(&motionArgs);
9045 }
9046};
9047
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009048using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9049
9050TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9051 ScopedSilentDeath _silentDeath;
9052
Prabir Pradhand65552b2021-10-07 11:23:50 -07009053 auto [overlay, window] = setupStylusOverlayScenario();
9054 overlay->setTrustedOverlay(false);
9055 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9056 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9057 ".* not a trusted overlay");
9058}
9059
9060TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9061 auto [overlay, window] = setupStylusOverlayScenario();
9062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9063
9064 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9065 overlay->consumeMotionDown();
9066 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9067 overlay->consumeMotionUp();
9068
9069 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9070 window->consumeMotionDown();
9071 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9072 window->consumeMotionUp();
9073
9074 overlay->assertNoEvents();
9075 window->assertNoEvents();
9076}
9077
9078TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9079 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009080 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9082
9083 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9084 overlay->consumeMotionDown();
9085 window->consumeMotionDown();
9086 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9087 overlay->consumeMotionUp();
9088 window->consumeMotionUp();
9089
9090 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9091 window->consumeMotionDown();
9092 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9093 window->consumeMotionUp();
9094
9095 overlay->assertNoEvents();
9096 window->assertNoEvents();
9097}
9098
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009099/**
9100 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9101 * The scenario is as follows:
9102 * - The stylus interceptor overlay is configured as a spy window.
9103 * - The stylus interceptor spy receives the start of a new stylus gesture.
9104 * - It pilfers pointers and then configures itself to no longer be a spy.
9105 * - The stylus interceptor continues to receive the rest of the gesture.
9106 */
9107TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9108 auto [overlay, window] = setupStylusOverlayScenario();
9109 overlay->setSpy(true);
9110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9111
9112 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9113 overlay->consumeMotionDown();
9114 window->consumeMotionDown();
9115
9116 // The interceptor pilfers the pointers.
9117 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9118 window->consumeMotionCancel();
9119
9120 // The interceptor configures itself so that it is no longer a spy.
9121 overlay->setSpy(false);
9122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9123
9124 // It continues to receive the rest of the stylus gesture.
9125 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9126 overlay->consumeMotionMove();
9127 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9128 overlay->consumeMotionUp();
9129
9130 window->assertNoEvents();
9131}
9132
Prabir Pradhan5735a322022-04-11 17:23:34 +00009133struct User {
9134 int32_t mPid;
9135 int32_t mUid;
9136 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9137 std::unique_ptr<InputDispatcher>& mDispatcher;
9138
9139 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9140 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9141
9142 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9143 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9144 ADISPLAY_ID_DEFAULT, {100, 200},
9145 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9146 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9147 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9148 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9149 }
9150
9151 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009152 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009153 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009154 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009155 mPolicyFlags);
9156 }
9157
9158 sp<FakeWindowHandle> createWindow() const {
9159 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9160 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009161 sp<FakeWindowHandle> window =
9162 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9163 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009164 window->setOwnerInfo(mPid, mUid);
9165 return window;
9166 }
9167};
9168
9169using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9170
9171TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9172 auto owner = User(mDispatcher, 10, 11);
9173 auto window = owner.createWindow();
9174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9175
9176 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9177 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9178 window->consumeMotionDown();
9179
9180 setFocusedWindow(window);
9181 window->consumeFocusEvent(true);
9182
9183 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9184 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9185 window->consumeKeyDown(ADISPLAY_ID_NONE);
9186}
9187
9188TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9189 auto owner = User(mDispatcher, 10, 11);
9190 auto window = owner.createWindow();
9191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9192
9193 auto rando = User(mDispatcher, 20, 21);
9194 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9195 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9196
9197 setFocusedWindow(window);
9198 window->consumeFocusEvent(true);
9199
9200 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9201 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9202 window->assertNoEvents();
9203}
9204
9205TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9206 auto owner = User(mDispatcher, 10, 11);
9207 auto window = owner.createWindow();
9208 auto spy = owner.createWindow();
9209 spy->setSpy(true);
9210 spy->setTrustedOverlay(true);
9211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9212
9213 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9214 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9215 spy->consumeMotionDown();
9216 window->consumeMotionDown();
9217}
9218
9219TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9220 auto owner = User(mDispatcher, 10, 11);
9221 auto window = owner.createWindow();
9222
9223 auto rando = User(mDispatcher, 20, 21);
9224 auto randosSpy = rando.createWindow();
9225 randosSpy->setSpy(true);
9226 randosSpy->setTrustedOverlay(true);
9227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9228
9229 // The event is targeted at owner's window, so injection should succeed, but the spy should
9230 // not receive the event.
9231 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9232 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9233 randosSpy->assertNoEvents();
9234 window->consumeMotionDown();
9235}
9236
9237TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9238 auto owner = User(mDispatcher, 10, 11);
9239 auto window = owner.createWindow();
9240
9241 auto rando = User(mDispatcher, 20, 21);
9242 auto randosSpy = rando.createWindow();
9243 randosSpy->setSpy(true);
9244 randosSpy->setTrustedOverlay(true);
9245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9246
9247 // A user that has injection permission can inject into any window.
9248 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9249 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9250 ADISPLAY_ID_DEFAULT));
9251 randosSpy->consumeMotionDown();
9252 window->consumeMotionDown();
9253
9254 setFocusedWindow(randosSpy);
9255 randosSpy->consumeFocusEvent(true);
9256
9257 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9258 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9259 window->assertNoEvents();
9260}
9261
9262TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9263 auto owner = User(mDispatcher, 10, 11);
9264 auto window = owner.createWindow();
9265
9266 auto rando = User(mDispatcher, 20, 21);
9267 auto randosWindow = rando.createWindow();
9268 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9269 randosWindow->setWatchOutsideTouch(true);
9270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9271
9272 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9273 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9274 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9275 window->consumeMotionDown();
9276 randosWindow->consumeMotionOutside();
9277}
9278
Garfield Tane84e6f92019-08-29 17:28:41 -07009279} // namespace android::inputdispatcher