blob: bd9038d42e8f1b6156df94d54628a595d5484f5f [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
2493 // First touch pointer down on right window
2494 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 Vishniakou0b0374d2022-11-17 17:40:53 -08003443 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003444 * The tap causes a HOVER_EXIT event to be generated because the current event
3445 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003446 */
3447TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3449 sp<FakeWindowHandle> window =
3450 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3451 window->setFrame(Rect(0, 0, 100, 100));
3452
3453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3454
3455 // Inject a hover_move from mouse.
3456 NotifyMotionArgs motionArgs =
3457 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3458 ADISPLAY_ID_DEFAULT, {{50, 50}});
3459 motionArgs.xCursorPosition = 50;
3460 motionArgs.yCursorPosition = 50;
3461 mDispatcher->notifyMotion(&motionArgs);
3462 ASSERT_NO_FATAL_FAILURE(
3463 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3464 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003465
3466 // Tap on the window
3467 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3468 ADISPLAY_ID_DEFAULT, {{10, 10}});
3469 mDispatcher->notifyMotion(&motionArgs);
3470 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003471 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3472 WithSource(AINPUT_SOURCE_MOUSE))));
3473
3474 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003475 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3476 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3477
3478 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3479 ADISPLAY_ID_DEFAULT, {{10, 10}});
3480 mDispatcher->notifyMotion(&motionArgs);
3481 ASSERT_NO_FATAL_FAILURE(
3482 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3483 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3484}
3485
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003486TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3488 sp<FakeWindowHandle> windowDefaultDisplay =
3489 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3490 ADISPLAY_ID_DEFAULT);
3491 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3492 sp<FakeWindowHandle> windowSecondDisplay =
3493 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3494 SECOND_DISPLAY_ID);
3495 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3496
3497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3498 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3499
3500 // Set cursor position in window in default display and check that hover enter and move
3501 // events are generated.
3502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3503 injectMotionEvent(mDispatcher,
3504 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3505 AINPUT_SOURCE_MOUSE)
3506 .displayId(ADISPLAY_ID_DEFAULT)
3507 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3508 .x(300)
3509 .y(600))
3510 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003511 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003512
3513 // Remove all windows in secondary display and check that no event happens on window in
3514 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003515 mDispatcher->setInputWindows(
3516 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003517 windowDefaultDisplay->assertNoEvents();
3518
3519 // Move cursor position in window in default display and check that only hover move
3520 // event is generated and not hover enter event.
3521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3522 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3524 injectMotionEvent(mDispatcher,
3525 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3526 AINPUT_SOURCE_MOUSE)
3527 .displayId(ADISPLAY_ID_DEFAULT)
3528 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3529 .x(400)
3530 .y(700))
3531 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003532 windowDefaultDisplay->consumeMotionEvent(
3533 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3534 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003535 windowDefaultDisplay->assertNoEvents();
3536}
3537
Garfield Tan00f511d2019-06-12 16:55:40 -07003538TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003540
3541 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003542 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003543 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003544 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003545 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003546 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003547
3548 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3549
Arthur Hung72d8dc32020-03-28 00:48:39 +00003550 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003551
3552 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3553 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003555 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003556 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003557 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003558 windowRight->assertNoEvents();
3559}
3560
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003561TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003563 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3564 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003565 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003566
Arthur Hung72d8dc32020-03-28 00:48:39 +00003567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003568 setFocusedWindow(window);
3569
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003570 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003571
3572 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3573 mDispatcher->notifyKey(&keyArgs);
3574
3575 // Window should receive key down event.
3576 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3577
3578 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3579 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003580 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003581 mDispatcher->notifyDeviceReset(&args);
3582 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3583 AKEY_EVENT_FLAG_CANCELED);
3584}
3585
3586TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003588 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3589 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003590
Arthur Hung72d8dc32020-03-28 00:48:39 +00003591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003592
3593 NotifyMotionArgs motionArgs =
3594 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3595 ADISPLAY_ID_DEFAULT);
3596 mDispatcher->notifyMotion(&motionArgs);
3597
3598 // Window should receive motion down event.
3599 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3600
3601 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3602 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003603 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003604 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003605 window->consumeMotionEvent(
3606 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003607}
3608
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003609TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3610 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003611 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3612 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003613 window->setFocusable(true);
3614
3615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3616 setFocusedWindow(window);
3617
3618 window->consumeFocusEvent(true);
3619
3620 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3621 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3622 const nsecs_t injectTime = keyArgs.eventTime;
3623 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3624 mDispatcher->notifyKey(&keyArgs);
3625 // The dispatching time should be always greater than or equal to intercept key timeout.
3626 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3627 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3628 std::chrono::nanoseconds(interceptKeyTimeout).count());
3629}
3630
3631TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3632 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003633 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3634 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003635 window->setFocusable(true);
3636
3637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3638 setFocusedWindow(window);
3639
3640 window->consumeFocusEvent(true);
3641
3642 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3643 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3644 mFakePolicy->setInterceptKeyTimeout(150ms);
3645 mDispatcher->notifyKey(&keyDown);
3646 mDispatcher->notifyKey(&keyUp);
3647
3648 // Window should receive key event immediately when same key up.
3649 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3650 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3651}
3652
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003653/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003654 * Two windows. First is a regular window. Second does not overlap with the first, and has
3655 * WATCH_OUTSIDE_TOUCH.
3656 * Both windows are owned by the same UID.
3657 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3658 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3659 */
3660TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3662 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3663 "First Window", ADISPLAY_ID_DEFAULT);
3664 window->setFrame(Rect{0, 0, 100, 100});
3665
3666 sp<FakeWindowHandle> outsideWindow =
3667 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3668 ADISPLAY_ID_DEFAULT);
3669 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3670 outsideWindow->setWatchOutsideTouch(true);
3671 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3673
3674 // Tap on first window.
3675 NotifyMotionArgs motionArgs =
3676 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3677 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3678 mDispatcher->notifyMotion(&motionArgs);
3679 window->consumeMotionDown();
3680 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3681 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3682 outsideWindow->consumeMotionEvent(
3683 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3684}
3685
3686/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003687 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3688 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3689 * ACTION_OUTSIDE event is sent per gesture.
3690 */
3691TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3692 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3693 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003694 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3695 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003696 window->setWatchOutsideTouch(true);
3697 window->setFrame(Rect{0, 0, 100, 100});
3698 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003699 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3700 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003701 secondWindow->setFrame(Rect{100, 100, 200, 200});
3702 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003703 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3704 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003705 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3707
3708 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3709 NotifyMotionArgs motionArgs =
3710 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3711 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3712 mDispatcher->notifyMotion(&motionArgs);
3713 window->assertNoEvents();
3714 secondWindow->assertNoEvents();
3715
3716 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3717 // Now, `window` should get ACTION_OUTSIDE.
3718 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3719 {PointF{-10, -10}, PointF{105, 105}});
3720 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003721 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3722 window->consumeMotionEvent(
3723 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003724 secondWindow->consumeMotionDown();
3725 thirdWindow->assertNoEvents();
3726
3727 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3728 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3729 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3730 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3731 mDispatcher->notifyMotion(&motionArgs);
3732 window->assertNoEvents();
3733 secondWindow->consumeMotionMove();
3734 thirdWindow->consumeMotionDown();
3735}
3736
Prabir Pradhan814fe082022-07-22 20:22:18 +00003737TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3738 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003739 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3740 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003741 window->setFocusable(true);
3742
3743 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3744 setFocusedWindow(window);
3745
3746 window->consumeFocusEvent(true);
3747
3748 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3749 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3750 mDispatcher->notifyKey(&keyDown);
3751 mDispatcher->notifyKey(&keyUp);
3752
3753 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3754 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3755
3756 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3757 mDispatcher->onWindowInfosChanged({}, {});
3758
3759 window->consumeFocusEvent(false);
3760
3761 mDispatcher->notifyKey(&keyDown);
3762 mDispatcher->notifyKey(&keyUp);
3763 window->assertNoEvents();
3764}
3765
Arthur Hung96483742022-11-15 03:30:48 +00003766TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3767 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3768 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3769 "Fake Window", ADISPLAY_ID_DEFAULT);
3770 // Ensure window is non-split and have some transform.
3771 window->setPreventSplitting(true);
3772 window->setWindowOffset(20, 40);
3773 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3774
3775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3776 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3777 {50, 50}))
3778 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3779 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3780
3781 const MotionEvent secondFingerDownEvent =
3782 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3783 .displayId(ADISPLAY_ID_DEFAULT)
3784 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003785 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3786 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003787 .build();
3788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3789 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3790 InputEventInjectionSync::WAIT_FOR_RESULT))
3791 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3792
3793 const MotionEvent* event = window->consumeMotion();
3794 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3795 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3796 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3797 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3798 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3799}
3800
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003801/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003802 * Ensure the correct coordinate spaces are used by InputDispatcher.
3803 *
3804 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3805 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3806 * space.
3807 */
3808class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3809public:
3810 void SetUp() override {
3811 InputDispatcherTest::SetUp();
3812 mDisplayInfos.clear();
3813 mWindowInfos.clear();
3814 }
3815
3816 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3817 gui::DisplayInfo info;
3818 info.displayId = displayId;
3819 info.transform = transform;
3820 mDisplayInfos.push_back(std::move(info));
3821 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3822 }
3823
3824 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3825 mWindowInfos.push_back(*windowHandle->getInfo());
3826 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3827 }
3828
3829 // Set up a test scenario where the display has a scaled projection and there are two windows
3830 // on the display.
3831 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3832 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3833 // respectively.
3834 ui::Transform displayTransform;
3835 displayTransform.set(2, 0, 0, 4);
3836 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3837
3838 std::shared_ptr<FakeApplicationHandle> application =
3839 std::make_shared<FakeApplicationHandle>();
3840
3841 // Add two windows to the display. Their frames are represented in the display space.
3842 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003843 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3844 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003845 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3846 addWindow(firstWindow);
3847
3848 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003849 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3850 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003851 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3852 addWindow(secondWindow);
3853 return {std::move(firstWindow), std::move(secondWindow)};
3854 }
3855
3856private:
3857 std::vector<gui::DisplayInfo> mDisplayInfos;
3858 std::vector<gui::WindowInfo> mWindowInfos;
3859};
3860
3861TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3862 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3863 // Send down to the first window. The point is represented in the display space. The point is
3864 // selected so that if the hit test was done with the transform applied to it, then it would
3865 // end up in the incorrect window.
3866 NotifyMotionArgs downMotionArgs =
3867 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3868 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3869 mDispatcher->notifyMotion(&downMotionArgs);
3870
3871 firstWindow->consumeMotionDown();
3872 secondWindow->assertNoEvents();
3873}
3874
3875// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3876// the event should be treated as being in the logical display space.
3877TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3878 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3879 // Send down to the first window. The point is represented in the logical display space. The
3880 // point is selected so that if the hit test was done in logical display space, then it would
3881 // end up in the incorrect window.
3882 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3883 PointF{75 * 2, 55 * 4});
3884
3885 firstWindow->consumeMotionDown();
3886 secondWindow->assertNoEvents();
3887}
3888
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003889// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3890// event should be treated as being in the logical display space.
3891TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3892 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3893
3894 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3895 ui::Transform injectedEventTransform;
3896 injectedEventTransform.set(matrix);
3897 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
3898 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
3899
3900 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3901 .displayId(ADISPLAY_ID_DEFAULT)
3902 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003903 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003904 .x(untransformedPoint.x)
3905 .y(untransformedPoint.y))
3906 .build();
3907 event.transform(matrix);
3908
3909 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
3910 InputEventInjectionSync::WAIT_FOR_RESULT);
3911
3912 firstWindow->consumeMotionDown();
3913 secondWindow->assertNoEvents();
3914}
3915
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003916TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
3917 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3918
3919 // Send down to the second window.
3920 NotifyMotionArgs downMotionArgs =
3921 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3922 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
3923 mDispatcher->notifyMotion(&downMotionArgs);
3924
3925 firstWindow->assertNoEvents();
3926 const MotionEvent* event = secondWindow->consumeMotion();
3927 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
3928
3929 // Ensure that the events from the "getRaw" API are in logical display coordinates.
3930 EXPECT_EQ(300, event->getRawX(0));
3931 EXPECT_EQ(880, event->getRawY(0));
3932
3933 // Ensure that the x and y values are in the window's coordinate space.
3934 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
3935 // the logical display space. This will be the origin of the window space.
3936 EXPECT_EQ(100, event->getX(0));
3937 EXPECT_EQ(80, event->getY(0));
3938}
3939
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003940using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
3941 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003942
3943class TransferTouchFixture : public InputDispatcherTest,
3944 public ::testing::WithParamInterface<TransferFunction> {};
3945
3946TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07003947 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003948
3949 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003950 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003951 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3952 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003953 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003954 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003955 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3956 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003957 sp<FakeWindowHandle> wallpaper =
3958 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
3959 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003960 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00003961 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003962
3963 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003964 NotifyMotionArgs downMotionArgs =
3965 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3966 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003967 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003968
Svet Ganov5d3bc372020-01-26 23:11:07 -08003969 // Only the first window should get the down event
3970 firstWindow->consumeMotionDown();
3971 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003972 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003973
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003974 // Transfer touch to the second window
3975 TransferFunction f = GetParam();
3976 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3977 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003978 // The first window gets cancel and the second gets down
3979 firstWindow->consumeMotionCancel();
3980 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003981 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003982
3983 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003984 NotifyMotionArgs upMotionArgs =
3985 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3986 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003987 mDispatcher->notifyMotion(&upMotionArgs);
3988 // The first window gets no events and the second gets up
3989 firstWindow->assertNoEvents();
3990 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003991 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003992}
3993
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003994/**
3995 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
3996 * from. When we have spy windows, there are several windows to choose from: either spy, or the
3997 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
3998 * natural to the user.
3999 * In this test, we are sending a pointer to both spy window and first window. We then try to
4000 * transfer touch to the second window. The dispatcher should identify the first window as the
4001 * one that should lose the gesture, and therefore the action should be to move the gesture from
4002 * the first window to the second.
4003 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4004 * the other API, as well.
4005 */
4006TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4007 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4008
4009 // Create a couple of windows + a spy window
4010 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004011 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004012 spyWindow->setTrustedOverlay(true);
4013 spyWindow->setSpy(true);
4014 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004015 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004016 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004017 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004018
4019 // Add the windows to the dispatcher
4020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4021
4022 // Send down to the first window
4023 NotifyMotionArgs downMotionArgs =
4024 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4025 ADISPLAY_ID_DEFAULT);
4026 mDispatcher->notifyMotion(&downMotionArgs);
4027 // Only the first window and spy should get the down event
4028 spyWindow->consumeMotionDown();
4029 firstWindow->consumeMotionDown();
4030
4031 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4032 // if f === 'transferTouch'.
4033 TransferFunction f = GetParam();
4034 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4035 ASSERT_TRUE(success);
4036 // The first window gets cancel and the second gets down
4037 firstWindow->consumeMotionCancel();
4038 secondWindow->consumeMotionDown();
4039
4040 // Send up event to the second window
4041 NotifyMotionArgs upMotionArgs =
4042 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4043 ADISPLAY_ID_DEFAULT);
4044 mDispatcher->notifyMotion(&upMotionArgs);
4045 // The first window gets no events and the second+spy get up
4046 firstWindow->assertNoEvents();
4047 spyWindow->consumeMotionUp();
4048 secondWindow->consumeMotionUp();
4049}
4050
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004051TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004052 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004053
4054 PointF touchPoint = {10, 10};
4055
4056 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004057 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004058 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4059 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004060 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004061 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004062 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4063 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004064 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004065
4066 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004068
4069 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004070 NotifyMotionArgs downMotionArgs =
4071 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4072 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004073 mDispatcher->notifyMotion(&downMotionArgs);
4074 // Only the first window should get the down event
4075 firstWindow->consumeMotionDown();
4076 secondWindow->assertNoEvents();
4077
4078 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004079 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004080 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004081 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004082 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4083 // Only the first window should get the pointer down event
4084 firstWindow->consumeMotionPointerDown(1);
4085 secondWindow->assertNoEvents();
4086
4087 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004088 TransferFunction f = GetParam();
4089 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4090 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091 // The first window gets cancel and the second gets down and pointer down
4092 firstWindow->consumeMotionCancel();
4093 secondWindow->consumeMotionDown();
4094 secondWindow->consumeMotionPointerDown(1);
4095
4096 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004097 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004098 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004099 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4101 // The first window gets nothing and the second gets pointer up
4102 firstWindow->assertNoEvents();
4103 secondWindow->consumeMotionPointerUp(1);
4104
4105 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004106 NotifyMotionArgs upMotionArgs =
4107 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4108 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004109 mDispatcher->notifyMotion(&upMotionArgs);
4110 // The first window gets nothing and the second gets up
4111 firstWindow->assertNoEvents();
4112 secondWindow->consumeMotionUp();
4113}
4114
Arthur Hungc539dbb2022-12-08 07:45:36 +00004115TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4116 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4117
4118 // Create a couple of windows
4119 sp<FakeWindowHandle> firstWindow =
4120 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4121 ADISPLAY_ID_DEFAULT);
4122 firstWindow->setDupTouchToWallpaper(true);
4123 sp<FakeWindowHandle> secondWindow =
4124 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4125 ADISPLAY_ID_DEFAULT);
4126 secondWindow->setDupTouchToWallpaper(true);
4127
4128 sp<FakeWindowHandle> wallpaper1 =
4129 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4130 wallpaper1->setIsWallpaper(true);
4131
4132 sp<FakeWindowHandle> wallpaper2 =
4133 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4134 wallpaper2->setIsWallpaper(true);
4135 // Add the windows to the dispatcher
4136 mDispatcher->setInputWindows(
4137 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4138
4139 // Send down to the first window
4140 NotifyMotionArgs downMotionArgs =
4141 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4142 ADISPLAY_ID_DEFAULT);
4143 mDispatcher->notifyMotion(&downMotionArgs);
4144
4145 // Only the first window should get the down event
4146 firstWindow->consumeMotionDown();
4147 secondWindow->assertNoEvents();
4148 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4149 wallpaper2->assertNoEvents();
4150
4151 // Transfer touch focus to the second window
4152 TransferFunction f = GetParam();
4153 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4154 ASSERT_TRUE(success);
4155
4156 // The first window gets cancel and the second gets down
4157 firstWindow->consumeMotionCancel();
4158 secondWindow->consumeMotionDown();
4159 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4160 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4161
4162 // Send up event to the second window
4163 NotifyMotionArgs upMotionArgs =
4164 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4165 ADISPLAY_ID_DEFAULT);
4166 mDispatcher->notifyMotion(&upMotionArgs);
4167 // The first window gets no events and the second gets up
4168 firstWindow->assertNoEvents();
4169 secondWindow->consumeMotionUp();
4170 wallpaper1->assertNoEvents();
4171 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4172}
4173
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004174// For the cases of single pointer touch and two pointers non-split touch, the api's
4175// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4176// for the case where there are multiple pointers split across several windows.
4177INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4178 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004179 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4180 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004181 return dispatcher->transferTouch(destChannelToken,
4182 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004183 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004184 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4185 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004186 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004187 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004188 }));
4189
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004191 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004192
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004193 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004194 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4195 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004196 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004198 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004199 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4200 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004202
4203 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205
4206 PointF pointInFirst = {300, 200};
4207 PointF pointInSecond = {300, 600};
4208
4209 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004210 NotifyMotionArgs firstDownMotionArgs =
4211 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4212 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004213 mDispatcher->notifyMotion(&firstDownMotionArgs);
4214 // Only the first window should get the down event
4215 firstWindow->consumeMotionDown();
4216 secondWindow->assertNoEvents();
4217
4218 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004219 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004220 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004221 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004222 mDispatcher->notifyMotion(&secondDownMotionArgs);
4223 // The first window gets a move and the second a down
4224 firstWindow->consumeMotionMove();
4225 secondWindow->consumeMotionDown();
4226
4227 // Transfer touch focus to the second window
4228 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4229 // The first window gets cancel and the new gets pointer down (it already saw down)
4230 firstWindow->consumeMotionCancel();
4231 secondWindow->consumeMotionPointerDown(1);
4232
4233 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004234 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004235 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004236 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004237 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4238 // The first window gets nothing and the second gets pointer up
4239 firstWindow->assertNoEvents();
4240 secondWindow->consumeMotionPointerUp(1);
4241
4242 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004243 NotifyMotionArgs upMotionArgs =
4244 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4245 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 mDispatcher->notifyMotion(&upMotionArgs);
4247 // The first window gets nothing and the second gets up
4248 firstWindow->assertNoEvents();
4249 secondWindow->consumeMotionUp();
4250}
4251
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004252// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4253// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4254// touch is not supported, so the touch should continue on those windows and the transferred-to
4255// window should get nothing.
4256TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4257 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4258
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004259 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004260 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4261 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004262 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004263
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004264 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004265 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4266 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004267 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004268
4269 // Add the windows to the dispatcher
4270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4271
4272 PointF pointInFirst = {300, 200};
4273 PointF pointInSecond = {300, 600};
4274
4275 // Send down to the first window
4276 NotifyMotionArgs firstDownMotionArgs =
4277 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4278 ADISPLAY_ID_DEFAULT, {pointInFirst});
4279 mDispatcher->notifyMotion(&firstDownMotionArgs);
4280 // Only the first window should get the down event
4281 firstWindow->consumeMotionDown();
4282 secondWindow->assertNoEvents();
4283
4284 // Send down to the second window
4285 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004286 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004287 {pointInFirst, pointInSecond});
4288 mDispatcher->notifyMotion(&secondDownMotionArgs);
4289 // The first window gets a move and the second a down
4290 firstWindow->consumeMotionMove();
4291 secondWindow->consumeMotionDown();
4292
4293 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004294 const bool transferred =
4295 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004296 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4297 ASSERT_FALSE(transferred);
4298 firstWindow->assertNoEvents();
4299 secondWindow->assertNoEvents();
4300
4301 // The rest of the dispatch should proceed as normal
4302 // Send pointer up to the second window
4303 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004304 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004305 {pointInFirst, pointInSecond});
4306 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4307 // The first window gets MOVE and the second gets pointer up
4308 firstWindow->consumeMotionMove();
4309 secondWindow->consumeMotionUp();
4310
4311 // Send up event to the first window
4312 NotifyMotionArgs upMotionArgs =
4313 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4314 ADISPLAY_ID_DEFAULT);
4315 mDispatcher->notifyMotion(&upMotionArgs);
4316 // The first window gets nothing and the second gets up
4317 firstWindow->consumeMotionUp();
4318 secondWindow->assertNoEvents();
4319}
4320
Arthur Hungabbb9d82021-09-01 14:52:30 +00004321// This case will create two windows and one mirrored window on the default display and mirror
4322// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4323// the windows info of second display before default display.
4324TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4325 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4326 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004327 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004328 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004329 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004330 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004331 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004332
4333 sp<FakeWindowHandle> mirrorWindowInPrimary =
4334 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4335 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004336
4337 sp<FakeWindowHandle> firstWindowInSecondary =
4338 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4339 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004340
4341 sp<FakeWindowHandle> secondWindowInSecondary =
4342 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4343 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004344
4345 // Update window info, let it find window handle of second display first.
4346 mDispatcher->setInputWindows(
4347 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4348 {ADISPLAY_ID_DEFAULT,
4349 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4350
4351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4352 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4353 {50, 50}))
4354 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4355
4356 // Window should receive motion event.
4357 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4358
4359 // Transfer touch focus
4360 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4361 secondWindowInPrimary->getToken()));
4362 // The first window gets cancel.
4363 firstWindowInPrimary->consumeMotionCancel();
4364 secondWindowInPrimary->consumeMotionDown();
4365
4366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4367 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4368 ADISPLAY_ID_DEFAULT, {150, 50}))
4369 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4370 firstWindowInPrimary->assertNoEvents();
4371 secondWindowInPrimary->consumeMotionMove();
4372
4373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4374 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4375 {150, 50}))
4376 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4377 firstWindowInPrimary->assertNoEvents();
4378 secondWindowInPrimary->consumeMotionUp();
4379}
4380
4381// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4382// 'transferTouch' api.
4383TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4385 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004386 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004387 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004388 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004389 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004390 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004391
4392 sp<FakeWindowHandle> mirrorWindowInPrimary =
4393 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4394 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004395
4396 sp<FakeWindowHandle> firstWindowInSecondary =
4397 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4398 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004399
4400 sp<FakeWindowHandle> secondWindowInSecondary =
4401 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4402 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004403
4404 // Update window info, let it find window handle of second display first.
4405 mDispatcher->setInputWindows(
4406 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4407 {ADISPLAY_ID_DEFAULT,
4408 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4409
4410 // Touch on second display.
4411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4412 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4413 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4414
4415 // Window should receive motion event.
4416 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4417
4418 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004419 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004420
4421 // The first window gets cancel.
4422 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4423 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4424
4425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4426 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4427 SECOND_DISPLAY_ID, {150, 50}))
4428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4429 firstWindowInPrimary->assertNoEvents();
4430 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4431
4432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4433 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4435 firstWindowInPrimary->assertNoEvents();
4436 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4437}
4438
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004439TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004441 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4442 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004443
Vishnu Nair47074b82020-08-14 11:54:47 -07004444 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004446 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004447
4448 window->consumeFocusEvent(true);
4449
4450 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4451 mDispatcher->notifyKey(&keyArgs);
4452
4453 // Window should receive key down event.
4454 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4455}
4456
4457TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004458 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004459 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4460 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004461
Arthur Hung72d8dc32020-03-28 00:48:39 +00004462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004463
4464 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4465 mDispatcher->notifyKey(&keyArgs);
4466 mDispatcher->waitForIdle();
4467
4468 window->assertNoEvents();
4469}
4470
4471// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4472TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004473 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004474 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4475 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004476
Arthur Hung72d8dc32020-03-28 00:48:39 +00004477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004478
4479 // Send key
4480 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4481 mDispatcher->notifyKey(&keyArgs);
4482 // Send motion
4483 NotifyMotionArgs motionArgs =
4484 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4485 ADISPLAY_ID_DEFAULT);
4486 mDispatcher->notifyMotion(&motionArgs);
4487
4488 // Window should receive only the motion event
4489 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4490 window->assertNoEvents(); // Key event or focus event will not be received
4491}
4492
arthurhungea3f4fc2020-12-21 23:18:53 +08004493TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4494 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4495
arthurhungea3f4fc2020-12-21 23:18:53 +08004496 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004497 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4498 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004499 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004500
arthurhungea3f4fc2020-12-21 23:18:53 +08004501 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004502 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4503 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004504 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004505
4506 // Add the windows to the dispatcher
4507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4508
4509 PointF pointInFirst = {300, 200};
4510 PointF pointInSecond = {300, 600};
4511
4512 // Send down to the first window
4513 NotifyMotionArgs firstDownMotionArgs =
4514 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4515 ADISPLAY_ID_DEFAULT, {pointInFirst});
4516 mDispatcher->notifyMotion(&firstDownMotionArgs);
4517 // Only the first window should get the down event
4518 firstWindow->consumeMotionDown();
4519 secondWindow->assertNoEvents();
4520
4521 // Send down to the second window
4522 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004523 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004524 {pointInFirst, pointInSecond});
4525 mDispatcher->notifyMotion(&secondDownMotionArgs);
4526 // The first window gets a move and the second a down
4527 firstWindow->consumeMotionMove();
4528 secondWindow->consumeMotionDown();
4529
4530 // Send pointer cancel to the second window
4531 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004532 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004533 {pointInFirst, pointInSecond});
4534 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4535 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4536 // The first window gets move and the second gets cancel.
4537 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4538 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4539
4540 // Send up event.
4541 NotifyMotionArgs upMotionArgs =
4542 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4543 ADISPLAY_ID_DEFAULT);
4544 mDispatcher->notifyMotion(&upMotionArgs);
4545 // The first window gets up and the second gets nothing.
4546 firstWindow->consumeMotionUp();
4547 secondWindow->assertNoEvents();
4548}
4549
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004550TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4552
4553 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004554 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4556 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4557 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4558 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4559
Harry Cutts33476232023-01-30 19:57:29 +00004560 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004561 window->assertNoEvents();
4562 mDispatcher->waitForIdle();
4563}
4564
chaviwd1c23182019-12-20 18:44:56 -08004565class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004566public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004567 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004568 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004569 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004570 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004571 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004572 }
4573
chaviwd1c23182019-12-20 18:44:56 -08004574 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4575
4576 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4577 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4578 expectedDisplayId, expectedFlags);
4579 }
4580
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4582
4583 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4584
chaviwd1c23182019-12-20 18:44:56 -08004585 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4586 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4587 expectedDisplayId, expectedFlags);
4588 }
4589
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004590 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4591 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4592 expectedDisplayId, expectedFlags);
4593 }
4594
chaviwd1c23182019-12-20 18:44:56 -08004595 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4596 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4597 expectedDisplayId, expectedFlags);
4598 }
4599
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004600 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004601 mInputReceiver->consumeMotionEvent(
4602 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4603 WithDisplayId(expectedDisplayId),
4604 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004605 }
4606
Arthur Hungfbfa5722021-11-16 02:45:54 +00004607 void consumeMotionPointerDown(int32_t pointerIdx) {
4608 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4609 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4610 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004611 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004612 }
4613
Evan Rosky84f07f02021-04-16 10:42:42 -07004614 MotionEvent* consumeMotion() {
4615 InputEvent* event = mInputReceiver->consume();
4616 if (!event) {
4617 ADD_FAILURE() << "No event was produced";
4618 return nullptr;
4619 }
4620 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4621 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4622 return nullptr;
4623 }
4624 return static_cast<MotionEvent*>(event);
4625 }
4626
chaviwd1c23182019-12-20 18:44:56 -08004627 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4628
4629private:
4630 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004631};
4632
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004633using InputDispatcherMonitorTest = InputDispatcherTest;
4634
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004635/**
4636 * Two entities that receive touch: A window, and a global monitor.
4637 * The touch goes to the window, and then the window disappears.
4638 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4639 * for the monitor, as well.
4640 * 1. foregroundWindow
4641 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4642 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004643TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4645 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004646 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004647
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004648 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004649
4650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4652 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4653 {100, 200}))
4654 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4655
4656 // Both the foreground window and the global monitor should receive the touch down
4657 window->consumeMotionDown();
4658 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4659
4660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4661 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4662 ADISPLAY_ID_DEFAULT, {110, 200}))
4663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4664
4665 window->consumeMotionMove();
4666 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4667
4668 // Now the foreground window goes away
4669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4670 window->consumeMotionCancel();
4671 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4672
4673 // If more events come in, there will be no more foreground window to send them to. This will
4674 // cause a cancel for the monitor, as well.
4675 ASSERT_EQ(InputEventInjectionResult::FAILED,
4676 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4677 ADISPLAY_ID_DEFAULT, {120, 200}))
4678 << "Injection should fail because the window was removed";
4679 window->assertNoEvents();
4680 // Global monitor now gets the cancel
4681 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4682}
4683
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004684TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004685 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004686 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4687 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004688 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004689
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004690 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004691
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004695 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004696 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004697}
4698
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004699TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4700 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004701
Chris Yea209fde2020-07-22 13:54:51 -07004702 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004703 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4704 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004708 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004710 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004711 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004712
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004713 // Pilfer pointers from the monitor.
4714 // This should not do anything and the window should continue to receive events.
4715 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004716
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004718 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4719 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004721
4722 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4723 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004724}
4725
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004726TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004727 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004728 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4729 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4731 window->setWindowOffset(20, 40);
4732 window->setWindowTransform(0, 1, -1, 0);
4733
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004734 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004735
4736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4738 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4739 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4740 MotionEvent* event = monitor.consumeMotion();
4741 // Even though window has transform, gesture monitor must not.
4742 ASSERT_EQ(ui::Transform(), event->getTransform());
4743}
4744
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004745TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004746 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004747 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004748
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004749 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004750 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004751 << "Injection should fail if there is a monitor, but no touchable window";
4752 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004753}
4754
chaviw81e2bb92019-12-18 15:03:51 -08004755TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004756 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004757 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4758 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004759
Arthur Hung72d8dc32020-03-28 00:48:39 +00004760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004761
4762 NotifyMotionArgs motionArgs =
4763 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4764 ADISPLAY_ID_DEFAULT);
4765
4766 mDispatcher->notifyMotion(&motionArgs);
4767 // Window should receive motion down event.
4768 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4769
4770 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004771 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004772 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4773 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4774 motionArgs.pointerCoords[0].getX() - 10);
4775
4776 mDispatcher->notifyMotion(&motionArgs);
4777 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004778 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004779}
4780
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004781/**
4782 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4783 * the device default right away. In the test scenario, we check both the default value,
4784 * and the action of enabling / disabling.
4785 */
4786TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004787 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004788 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4789 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004790 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004791
4792 // Set focused application.
4793 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004794 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004795
4796 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004798 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004799 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004800
4801 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004802 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004804 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004805
4806 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004807 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004808 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004809 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004810 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004812 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004813 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004814
4815 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004816 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004818 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004819
4820 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004821 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004822 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004823 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004824 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004826 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004827 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004828
4829 window->assertNoEvents();
4830}
4831
Gang Wange9087892020-01-07 12:17:14 -05004832TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004833 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004834 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4835 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004836
4837 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004838 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004839
Arthur Hung72d8dc32020-03-28 00:48:39 +00004840 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004841 setFocusedWindow(window);
4842
Harry Cutts33476232023-01-30 19:57:29 +00004843 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004844
4845 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4846 mDispatcher->notifyKey(&keyArgs);
4847
4848 InputEvent* event = window->consume();
4849 ASSERT_NE(event, nullptr);
4850
4851 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4852 ASSERT_NE(verified, nullptr);
4853 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4854
4855 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4856 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4857 ASSERT_EQ(keyArgs.source, verified->source);
4858 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4859
4860 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4861
4862 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004863 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004864 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004865 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4866 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4867 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4868 ASSERT_EQ(0, verifiedKey.repeatCount);
4869}
4870
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004871TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004873 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4874 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004875
4876 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4877
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004878 ui::Transform transform;
4879 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4880
4881 gui::DisplayInfo displayInfo;
4882 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
4883 displayInfo.transform = transform;
4884
4885 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004886
4887 NotifyMotionArgs motionArgs =
4888 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4889 ADISPLAY_ID_DEFAULT);
4890 mDispatcher->notifyMotion(&motionArgs);
4891
4892 InputEvent* event = window->consume();
4893 ASSERT_NE(event, nullptr);
4894
4895 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4896 ASSERT_NE(verified, nullptr);
4897 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
4898
4899 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
4900 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
4901 EXPECT_EQ(motionArgs.source, verified->source);
4902 EXPECT_EQ(motionArgs.displayId, verified->displayId);
4903
4904 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
4905
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004906 const vec2 rawXY =
4907 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
4908 motionArgs.pointerCoords[0].getXYValue());
4909 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
4910 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004911 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004912 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004913 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004914 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
4915 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
4916}
4917
chaviw09c8d2d2020-08-24 15:48:26 -07004918/**
4919 * Ensure that separate calls to sign the same data are generating the same key.
4920 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
4921 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
4922 * tests.
4923 */
4924TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
4925 KeyEvent event = getTestKeyEvent();
4926 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4927
4928 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
4929 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
4930 ASSERT_EQ(hmac1, hmac2);
4931}
4932
4933/**
4934 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
4935 */
4936TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
4937 KeyEvent event = getTestKeyEvent();
4938 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4939 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
4940
4941 verifiedEvent.deviceId += 1;
4942 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4943
4944 verifiedEvent.source += 1;
4945 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4946
4947 verifiedEvent.eventTimeNanos += 1;
4948 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4949
4950 verifiedEvent.displayId += 1;
4951 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4952
4953 verifiedEvent.action += 1;
4954 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4955
4956 verifiedEvent.downTimeNanos += 1;
4957 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4958
4959 verifiedEvent.flags += 1;
4960 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4961
4962 verifiedEvent.keyCode += 1;
4963 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4964
4965 verifiedEvent.scanCode += 1;
4966 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4967
4968 verifiedEvent.metaState += 1;
4969 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4970
4971 verifiedEvent.repeatCount += 1;
4972 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4973}
4974
Vishnu Nair958da932020-08-21 17:12:37 -07004975TEST_F(InputDispatcherTest, SetFocusedWindow) {
4976 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4977 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004978 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004979 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004980 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004981 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4982
4983 // Top window is also focusable but is not granted focus.
4984 windowTop->setFocusable(true);
4985 windowSecond->setFocusable(true);
4986 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4987 setFocusedWindow(windowSecond);
4988
4989 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4991 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004992
4993 // Focused window should receive event.
4994 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4995 windowTop->assertNoEvents();
4996}
4997
4998TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
4999 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5000 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005001 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005002 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5003
5004 window->setFocusable(true);
5005 // Release channel for window is no longer valid.
5006 window->releaseChannel();
5007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5008 setFocusedWindow(window);
5009
5010 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005011 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5012 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005013
5014 // window channel is invalid, so it should not receive any input event.
5015 window->assertNoEvents();
5016}
5017
5018TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5019 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5020 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005021 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005022 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005023 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5024
Vishnu Nair958da932020-08-21 17:12:37 -07005025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5026 setFocusedWindow(window);
5027
5028 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005029 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5030 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005031
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005032 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005033 window->assertNoEvents();
5034}
5035
5036TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5037 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5038 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005039 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005040 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005041 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005042 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5043
5044 windowTop->setFocusable(true);
5045 windowSecond->setFocusable(true);
5046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5047 setFocusedWindow(windowTop);
5048 windowTop->consumeFocusEvent(true);
5049
5050 setFocusedWindow(windowSecond, windowTop);
5051 windowSecond->consumeFocusEvent(true);
5052 windowTop->consumeFocusEvent(false);
5053
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5055 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005056
5057 // Focused window should receive event.
5058 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5059}
5060
5061TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5062 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5063 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005064 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005065 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005066 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005067 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5068
5069 windowTop->setFocusable(true);
5070 windowSecond->setFocusable(true);
5071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5072 setFocusedWindow(windowSecond, windowTop);
5073
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005074 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5075 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005076
5077 // Event should be dropped.
5078 windowTop->assertNoEvents();
5079 windowSecond->assertNoEvents();
5080}
5081
5082TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5083 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5084 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005085 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005086 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005087 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5088 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005089 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5090
5091 window->setFocusable(true);
5092 previousFocusedWindow->setFocusable(true);
5093 window->setVisible(false);
5094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5095 setFocusedWindow(previousFocusedWindow);
5096 previousFocusedWindow->consumeFocusEvent(true);
5097
5098 // Requesting focus on invisible window takes focus from currently focused window.
5099 setFocusedWindow(window);
5100 previousFocusedWindow->consumeFocusEvent(false);
5101
5102 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005104 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5105 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005106
5107 // Window does not get focus event or key down.
5108 window->assertNoEvents();
5109
5110 // Window becomes visible.
5111 window->setVisible(true);
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5113
5114 // Window receives focus event.
5115 window->consumeFocusEvent(true);
5116 // Focused window receives key down.
5117 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5118}
5119
Vishnu Nair599f1412021-06-21 10:39:58 -07005120TEST_F(InputDispatcherTest, DisplayRemoved) {
5121 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5122 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005123 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5125
5126 // window is granted focus.
5127 window->setFocusable(true);
5128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5129 setFocusedWindow(window);
5130 window->consumeFocusEvent(true);
5131
5132 // When a display is removed window loses focus.
5133 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5134 window->consumeFocusEvent(false);
5135}
5136
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005137/**
5138 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5139 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5140 * of the 'slipperyEnterWindow'.
5141 *
5142 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5143 * a way so that the touched location is no longer covered by the top window.
5144 *
5145 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5146 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5147 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5148 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5149 * with ACTION_DOWN).
5150 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5151 * window moved itself away from the touched location and had Flag::SLIPPERY.
5152 *
5153 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5154 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5155 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5156 *
5157 * In this test, we ensure that the event received by the bottom window has
5158 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5159 */
5160TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005161 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5162 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005163
5164 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5165 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5166
5167 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005168 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005169 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005170 // Make sure this one overlaps the bottom window
5171 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5172 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5173 // one. Windows with the same owner are not considered to be occluding each other.
5174 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5175
5176 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005177 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005178 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5179
5180 mDispatcher->setInputWindows(
5181 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5182
5183 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5184 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5185 ADISPLAY_ID_DEFAULT, {{50, 50}});
5186 mDispatcher->notifyMotion(&args);
5187 slipperyExitWindow->consumeMotionDown();
5188 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5189 mDispatcher->setInputWindows(
5190 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5191
5192 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5193 ADISPLAY_ID_DEFAULT, {{51, 51}});
5194 mDispatcher->notifyMotion(&args);
5195
5196 slipperyExitWindow->consumeMotionCancel();
5197
5198 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5199 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5200}
5201
Garfield Tan1c7bc862020-01-28 13:24:04 -08005202class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5203protected:
5204 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5205 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5206
Chris Yea209fde2020-07-22 13:54:51 -07005207 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005208 sp<FakeWindowHandle> mWindow;
5209
5210 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005211 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005212 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005213 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005214 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5215 ASSERT_EQ(OK, mDispatcher->start());
5216
5217 setUpWindow();
5218 }
5219
5220 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005221 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005222 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005223
Vishnu Nair47074b82020-08-14 11:54:47 -07005224 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005226 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005227 mWindow->consumeFocusEvent(true);
5228 }
5229
Chris Ye2ad95392020-09-01 13:44:44 -07005230 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005231 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005232 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005233 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5234 mDispatcher->notifyKey(&keyArgs);
5235
5236 // Window should receive key down event.
5237 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5238 }
5239
5240 void expectKeyRepeatOnce(int32_t repeatCount) {
5241 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5242 InputEvent* repeatEvent = mWindow->consume();
5243 ASSERT_NE(nullptr, repeatEvent);
5244
5245 uint32_t eventType = repeatEvent->getType();
5246 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5247
5248 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5249 uint32_t eventAction = repeatKeyEvent->getAction();
5250 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5251 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5252 }
5253
Chris Ye2ad95392020-09-01 13:44:44 -07005254 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005255 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005256 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005257 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5258 mDispatcher->notifyKey(&keyArgs);
5259
5260 // Window should receive key down event.
5261 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005262 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005263 }
5264};
5265
5266TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005267 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005268 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5269 expectKeyRepeatOnce(repeatCount);
5270 }
5271}
5272
5273TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005274 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005275 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5276 expectKeyRepeatOnce(repeatCount);
5277 }
Harry Cutts33476232023-01-30 19:57:29 +00005278 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005279 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005280 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5281 expectKeyRepeatOnce(repeatCount);
5282 }
5283}
5284
5285TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005286 sendAndConsumeKeyDown(/*deviceId=*/1);
5287 expectKeyRepeatOnce(/*repeatCount=*/1);
5288 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005289 mWindow->assertNoEvents();
5290}
5291
5292TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005293 sendAndConsumeKeyDown(/*deviceId=*/1);
5294 expectKeyRepeatOnce(/*repeatCount=*/1);
5295 sendAndConsumeKeyDown(/*deviceId=*/2);
5296 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005297 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005298 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005299 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005300 expectKeyRepeatOnce(/*repeatCount=*/2);
5301 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005302 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005303 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005304 mWindow->assertNoEvents();
5305}
5306
5307TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005308 sendAndConsumeKeyDown(/*deviceId=*/1);
5309 expectKeyRepeatOnce(/*repeatCount=*/1);
5310 sendAndConsumeKeyDown(/*deviceId=*/2);
5311 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005312 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005313 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005314 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005315 mWindow->assertNoEvents();
5316}
5317
liushenxiang42232912021-05-21 20:24:09 +08005318TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5319 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005320 expectKeyRepeatOnce(/*repeatCount=*/1);
5321 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005322 mDispatcher->notifyDeviceReset(&args);
5323 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5324 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5325 mWindow->assertNoEvents();
5326}
5327
Garfield Tan1c7bc862020-01-28 13:24:04 -08005328TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Harry Cutts33476232023-01-30 19:57:29 +00005329 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005330 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5331 InputEvent* repeatEvent = mWindow->consume();
5332 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5333 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5334 IdGenerator::getSource(repeatEvent->getId()));
5335 }
5336}
5337
5338TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Harry Cutts33476232023-01-30 19:57:29 +00005339 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005340
5341 std::unordered_set<int32_t> idSet;
5342 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5343 InputEvent* repeatEvent = mWindow->consume();
5344 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5345 int32_t id = repeatEvent->getId();
5346 EXPECT_EQ(idSet.end(), idSet.find(id));
5347 idSet.insert(id);
5348 }
5349}
5350
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005351/* Test InputDispatcher for MultiDisplay */
5352class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5353public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005354 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005355 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005356
Chris Yea209fde2020-07-22 13:54:51 -07005357 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005358 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005359 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005360
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005361 // Set focus window for primary display, but focused display would be second one.
5362 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005363 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005365 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005366 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005367
Chris Yea209fde2020-07-22 13:54:51 -07005368 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005369 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005370 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005371 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005372 // Set focus display to second one.
5373 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5374 // Set focus window for second display.
5375 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005376 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005377 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005378 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005379 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005380 }
5381
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005382 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005383 InputDispatcherTest::TearDown();
5384
Chris Yea209fde2020-07-22 13:54:51 -07005385 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005386 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005387 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005388 windowInSecondary.clear();
5389 }
5390
5391protected:
Chris Yea209fde2020-07-22 13:54:51 -07005392 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005393 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005394 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005395 sp<FakeWindowHandle> windowInSecondary;
5396};
5397
5398TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5399 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005403 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005404 windowInSecondary->assertNoEvents();
5405
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005406 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5408 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5409 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005410 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005411 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005412}
5413
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005414TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005415 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5417 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005418 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005419 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005420 windowInSecondary->assertNoEvents();
5421
5422 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005424 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005425 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005426 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005427
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005428 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005429 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005430
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005431 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005432 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5433 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005434
5435 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005436 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005437 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005438 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005439 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005440 windowInSecondary->assertNoEvents();
5441}
5442
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005443// Test per-display input monitors for motion event.
5444TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005445 FakeMonitorReceiver monitorInPrimary =
5446 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5447 FakeMonitorReceiver monitorInSecondary =
5448 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005449
5450 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5452 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005454 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005455 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005456 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005457 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005458
5459 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5461 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005463 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005464 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005465 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005466 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005467
5468 // Test inject a non-pointer motion event.
5469 // If specific a display, it will dispatch to the focused window of particular display,
5470 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5472 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5473 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005474 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005475 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005476 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005477 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005478}
5479
5480// Test per-display input monitors for key event.
5481TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005482 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005483 FakeMonitorReceiver monitorInPrimary =
5484 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5485 FakeMonitorReceiver monitorInSecondary =
5486 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005487
5488 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005489 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5490 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005491 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005492 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005493 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005494 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005495}
5496
Vishnu Nair958da932020-08-21 17:12:37 -07005497TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5498 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005499 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005500 secondWindowInPrimary->setFocusable(true);
5501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5502 setFocusedWindow(secondWindowInPrimary);
5503 windowInPrimary->consumeFocusEvent(false);
5504 secondWindowInPrimary->consumeFocusEvent(true);
5505
5506 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5508 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005509 windowInPrimary->assertNoEvents();
5510 windowInSecondary->assertNoEvents();
5511 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5512}
5513
Arthur Hungdfd528e2021-12-08 13:23:04 +00005514TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5515 FakeMonitorReceiver monitorInPrimary =
5516 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5517 FakeMonitorReceiver monitorInSecondary =
5518 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5519
5520 // Test touch down on primary display.
5521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5522 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5523 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5524 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5525 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5526
5527 // Test touch down on second display.
5528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5529 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5530 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5531 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5532 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5533
5534 // Trigger cancel touch.
5535 mDispatcher->cancelCurrentTouch();
5536 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5537 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5538 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5539 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5540
5541 // Test inject a move motion event, no window/monitor should receive the event.
5542 ASSERT_EQ(InputEventInjectionResult::FAILED,
5543 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5544 ADISPLAY_ID_DEFAULT, {110, 200}))
5545 << "Inject motion event should return InputEventInjectionResult::FAILED";
5546 windowInPrimary->assertNoEvents();
5547 monitorInPrimary.assertNoEvents();
5548
5549 ASSERT_EQ(InputEventInjectionResult::FAILED,
5550 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5551 SECOND_DISPLAY_ID, {110, 200}))
5552 << "Inject motion event should return InputEventInjectionResult::FAILED";
5553 windowInSecondary->assertNoEvents();
5554 monitorInSecondary.assertNoEvents();
5555}
5556
Jackal Guof9696682018-10-05 12:23:23 +08005557class InputFilterTest : public InputDispatcherTest {
5558protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005559 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5560 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005561 NotifyMotionArgs motionArgs;
5562
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005563 motionArgs =
5564 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005565 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005566 motionArgs =
5567 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005568 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005569 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005570 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005571 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5572 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005573 } else {
5574 mFakePolicy->assertFilterInputEventWasNotCalled();
5575 }
5576 }
5577
5578 void testNotifyKey(bool expectToBeFiltered) {
5579 NotifyKeyArgs keyArgs;
5580
5581 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5582 mDispatcher->notifyKey(&keyArgs);
5583 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5584 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005585 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005586
5587 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005588 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005589 } else {
5590 mFakePolicy->assertFilterInputEventWasNotCalled();
5591 }
5592 }
5593};
5594
5595// Test InputFilter for MotionEvent
5596TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5597 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5598 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5599 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5600
5601 // Enable InputFilter
5602 mDispatcher->setInputFilterEnabled(true);
5603 // Test touch on both primary and second display, and check if both events are filtered.
5604 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5605 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5606
5607 // Disable InputFilter
5608 mDispatcher->setInputFilterEnabled(false);
5609 // Test touch on both primary and second display, and check if both events aren't filtered.
5610 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5611 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5612}
5613
5614// Test InputFilter for KeyEvent
5615TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5616 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5617 testNotifyKey(/*expectToBeFiltered*/ false);
5618
5619 // Enable InputFilter
5620 mDispatcher->setInputFilterEnabled(true);
5621 // Send a key event, and check if it is filtered.
5622 testNotifyKey(/*expectToBeFiltered*/ true);
5623
5624 // Disable InputFilter
5625 mDispatcher->setInputFilterEnabled(false);
5626 // Send a key event, and check if it isn't filtered.
5627 testNotifyKey(/*expectToBeFiltered*/ false);
5628}
5629
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005630// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5631// logical display coordinate space.
5632TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5633 ui::Transform firstDisplayTransform;
5634 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5635 ui::Transform secondDisplayTransform;
5636 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5637
5638 std::vector<gui::DisplayInfo> displayInfos(2);
5639 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5640 displayInfos[0].transform = firstDisplayTransform;
5641 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5642 displayInfos[1].transform = secondDisplayTransform;
5643
5644 mDispatcher->onWindowInfosChanged({}, displayInfos);
5645
5646 // Enable InputFilter
5647 mDispatcher->setInputFilterEnabled(true);
5648
5649 // Ensure the correct transforms are used for the displays.
5650 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5651 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5652}
5653
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005654class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5655protected:
5656 virtual void SetUp() override {
5657 InputDispatcherTest::SetUp();
5658
5659 /**
5660 * We don't need to enable input filter to test the injected event policy, but we enabled it
5661 * here to make the tests more realistic, since this policy only matters when inputfilter is
5662 * on.
5663 */
5664 mDispatcher->setInputFilterEnabled(true);
5665
5666 std::shared_ptr<InputApplicationHandle> application =
5667 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005668 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5669 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005670
5671 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5672 mWindow->setFocusable(true);
5673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5674 setFocusedWindow(mWindow);
5675 mWindow->consumeFocusEvent(true);
5676 }
5677
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005678 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5679 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005680 KeyEvent event;
5681
5682 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5683 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5684 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005685 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005686 const int32_t additionalPolicyFlags =
5687 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005689 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005690 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5691 policyFlags | additionalPolicyFlags));
5692
5693 InputEvent* received = mWindow->consume();
5694 ASSERT_NE(nullptr, received);
5695 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005696 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5697 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5698 ASSERT_EQ(flags, keyEvent.getFlags());
5699 }
5700
5701 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5702 int32_t flags) {
5703 MotionEvent event;
5704 PointerProperties pointerProperties[1];
5705 PointerCoords pointerCoords[1];
5706 pointerProperties[0].clear();
5707 pointerProperties[0].id = 0;
5708 pointerCoords[0].clear();
5709 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5710 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5711
5712 ui::Transform identityTransform;
5713 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5714 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5715 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5716 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5717 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005718 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005719 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005720 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5721
5722 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005724 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005725 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5726 policyFlags | additionalPolicyFlags));
5727
5728 InputEvent* received = mWindow->consume();
5729 ASSERT_NE(nullptr, received);
5730 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5731 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5732 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5733 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005734 }
5735
5736private:
5737 sp<FakeWindowHandle> mWindow;
5738};
5739
5740TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005741 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5742 // filter. Without it, the event will no different from a regularly injected event, and the
5743 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005744 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5745 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005746}
5747
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005748TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005749 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005750 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005751 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5752}
5753
5754TEST_F(InputFilterInjectionPolicyTest,
5755 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5756 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005757 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005758 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005759}
5760
5761TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005762 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5763 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005764}
5765
chaviwfd6d3512019-03-25 13:23:49 -07005766class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005767 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005768 InputDispatcherTest::SetUp();
5769
Chris Yea209fde2020-07-22 13:54:51 -07005770 std::shared_ptr<FakeApplicationHandle> application =
5771 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005772 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005773 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005774 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005775
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005776 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005777 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005778 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005779
5780 // Set focused application.
5781 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005782 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005783
5784 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005786 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005787 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005788 }
5789
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005790 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005791 InputDispatcherTest::TearDown();
5792
5793 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005794 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005795 }
5796
5797protected:
5798 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005799 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005800 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005801};
5802
5803// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5804// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5805// the onPointerDownOutsideFocus callback.
5806TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005808 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5809 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005811 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005812
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005813 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005814 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5815}
5816
5817// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5818// DOWN on the window that doesn't have focus. Ensure no window received the
5819// onPointerDownOutsideFocus callback.
5820TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005824 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005825
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005826 ASSERT_TRUE(mDispatcher->waitForIdle());
5827 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005828}
5829
5830// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5831// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5832TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5834 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005835 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005836 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005837
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005838 ASSERT_TRUE(mDispatcher->waitForIdle());
5839 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005840}
5841
5842// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5843// DOWN on the window that already has focus. Ensure no window received the
5844// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005845TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005847 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005848 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005849 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005850 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005851
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005852 ASSERT_TRUE(mDispatcher->waitForIdle());
5853 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005854}
5855
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005856// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5857// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5858TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5859 const MotionEvent event =
5860 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5861 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005862 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005863 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
5864 .build();
5865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
5866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5867 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
5868
5869 ASSERT_TRUE(mDispatcher->waitForIdle());
5870 mFakePolicy->assertOnPointerDownWasNotCalled();
5871 // Ensure that the unfocused window did not receive any FOCUS events.
5872 mUnfocusedWindow->assertNoEvents();
5873}
5874
chaviwaf87b3e2019-10-01 16:59:28 -07005875// These tests ensures we can send touch events to a single client when there are multiple input
5876// windows that point to the same client token.
5877class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
5878 virtual void SetUp() override {
5879 InputDispatcherTest::SetUp();
5880
Chris Yea209fde2020-07-22 13:54:51 -07005881 std::shared_ptr<FakeApplicationHandle> application =
5882 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005883 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
5884 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07005885 mWindow1->setFrame(Rect(0, 0, 100, 100));
5886
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005887 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
5888 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07005889 mWindow2->setFrame(Rect(100, 100, 200, 200));
5890
Arthur Hung72d8dc32020-03-28 00:48:39 +00005891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07005892 }
5893
5894protected:
5895 sp<FakeWindowHandle> mWindow1;
5896 sp<FakeWindowHandle> mWindow2;
5897
5898 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05005899 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07005900 vec2 vals = windowInfo->transform.transform(point.x, point.y);
5901 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07005902 }
5903
5904 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
5905 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005906 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07005907 InputEvent* event = window->consume();
5908
5909 ASSERT_NE(nullptr, event) << name.c_str()
5910 << ": consumer should have returned non-NULL event.";
5911
5912 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
5913 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
5914 << " event, got " << inputEventTypeToString(event->getType()) << " event";
5915
5916 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005917 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08005918 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07005919
5920 for (size_t i = 0; i < points.size(); i++) {
5921 float expectedX = points[i].x;
5922 float expectedY = points[i].y;
5923
5924 EXPECT_EQ(expectedX, motionEvent.getX(i))
5925 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
5926 << ", got " << motionEvent.getX(i);
5927 EXPECT_EQ(expectedY, motionEvent.getY(i))
5928 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
5929 << ", got " << motionEvent.getY(i);
5930 }
5931 }
chaviw9eaa22c2020-07-01 16:21:27 -07005932
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005933 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07005934 std::vector<PointF> expectedPoints) {
5935 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
5936 ADISPLAY_ID_DEFAULT, touchedPoints);
5937 mDispatcher->notifyMotion(&motionArgs);
5938
5939 // Always consume from window1 since it's the window that has the InputReceiver
5940 consumeMotionEvent(mWindow1, action, expectedPoints);
5941 }
chaviwaf87b3e2019-10-01 16:59:28 -07005942};
5943
5944TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
5945 // Touch Window 1
5946 PointF touchedPoint = {10, 10};
5947 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005948 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005949
5950 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005951 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005952
5953 // Touch Window 2
5954 touchedPoint = {150, 150};
5955 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005956 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005957}
5958
chaviw9eaa22c2020-07-01 16:21:27 -07005959TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
5960 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07005961 mWindow2->setWindowScale(0.5f, 0.5f);
5962
5963 // Touch Window 1
5964 PointF touchedPoint = {10, 10};
5965 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005966 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005967 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005968 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005969
5970 // Touch Window 2
5971 touchedPoint = {150, 150};
5972 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005973 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
5974 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005975
chaviw9eaa22c2020-07-01 16:21:27 -07005976 // Update the transform so rotation is set
5977 mWindow2->setWindowTransform(0, -1, 1, 0);
5978 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
5979 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005980}
5981
chaviw9eaa22c2020-07-01 16:21:27 -07005982TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005983 mWindow2->setWindowScale(0.5f, 0.5f);
5984
5985 // Touch Window 1
5986 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5987 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005988 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005989
5990 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005991 touchedPoints.push_back(PointF{150, 150});
5992 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005993 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005994
chaviw9eaa22c2020-07-01 16:21:27 -07005995 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005996 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005997 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005998
chaviw9eaa22c2020-07-01 16:21:27 -07005999 // Update the transform so rotation is set for Window 2
6000 mWindow2->setWindowTransform(0, -1, 1, 0);
6001 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006002 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006003}
6004
chaviw9eaa22c2020-07-01 16:21:27 -07006005TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006006 mWindow2->setWindowScale(0.5f, 0.5f);
6007
6008 // Touch Window 1
6009 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6010 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006011 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006012
6013 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006014 touchedPoints.push_back(PointF{150, 150});
6015 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006016
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006017 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006018
6019 // Move both windows
6020 touchedPoints = {{20, 20}, {175, 175}};
6021 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6022 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6023
chaviw9eaa22c2020-07-01 16:21:27 -07006024 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006025
chaviw9eaa22c2020-07-01 16:21:27 -07006026 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006027 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006028 expectedPoints.pop_back();
6029
6030 // Touch Window 2
6031 mWindow2->setWindowTransform(0, -1, 1, 0);
6032 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006033 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006034
6035 // Move both windows
6036 touchedPoints = {{20, 20}, {175, 175}};
6037 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6038 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6039
6040 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006041}
6042
6043TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6044 mWindow1->setWindowScale(0.5f, 0.5f);
6045
6046 // Touch Window 1
6047 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6048 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006049 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006050
6051 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006052 touchedPoints.push_back(PointF{150, 150});
6053 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006054
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006055 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006056
6057 // Move both windows
6058 touchedPoints = {{20, 20}, {175, 175}};
6059 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6060 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6061
chaviw9eaa22c2020-07-01 16:21:27 -07006062 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006063}
6064
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006065class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6066 virtual void SetUp() override {
6067 InputDispatcherTest::SetUp();
6068
Chris Yea209fde2020-07-22 13:54:51 -07006069 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006070 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006071 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6072 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006073 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006074 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006075 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006076
6077 // Set focused application.
6078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6079
6080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006081 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006082 mWindow->consumeFocusEvent(true);
6083 }
6084
6085 virtual void TearDown() override {
6086 InputDispatcherTest::TearDown();
6087 mWindow.clear();
6088 }
6089
6090protected:
Chris Yea209fde2020-07-22 13:54:51 -07006091 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006092 sp<FakeWindowHandle> mWindow;
6093 static constexpr PointF WINDOW_LOCATION = {20, 20};
6094
6095 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006097 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6098 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006100 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6101 WINDOW_LOCATION));
6102 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006103
6104 sp<FakeWindowHandle> addSpyWindow() {
6105 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006106 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006107 spy->setTrustedOverlay(true);
6108 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006109 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006110 spy->setDispatchingTimeout(30ms);
6111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6112 return spy;
6113 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006114};
6115
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006116// Send a tap and respond, which should not cause an ANR.
6117TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6118 tapOnWindow();
6119 mWindow->consumeMotionDown();
6120 mWindow->consumeMotionUp();
6121 ASSERT_TRUE(mDispatcher->waitForIdle());
6122 mFakePolicy->assertNotifyAnrWasNotCalled();
6123}
6124
6125// Send a regular key and respond, which should not cause an ANR.
6126TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006127 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006128 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6129 ASSERT_TRUE(mDispatcher->waitForIdle());
6130 mFakePolicy->assertNotifyAnrWasNotCalled();
6131}
6132
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006133TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6134 mWindow->setFocusable(false);
6135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6136 mWindow->consumeFocusEvent(false);
6137
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006138 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006139 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6140 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6141 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006143 // Key will not go to window because we have no focused window.
6144 // The 'no focused window' ANR timer should start instead.
6145
6146 // Now, the focused application goes away.
6147 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6148 // The key should get dropped and there should be no ANR.
6149
6150 ASSERT_TRUE(mDispatcher->waitForIdle());
6151 mFakePolicy->assertNotifyAnrWasNotCalled();
6152}
6153
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006154// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006155// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6156// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006157TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006159 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6160 WINDOW_LOCATION));
6161
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006162 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6163 ASSERT_TRUE(sequenceNum);
6164 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006165 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006166
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006167 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006168 mWindow->consumeMotionEvent(
6169 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006170 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006171 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006172}
6173
6174// Send a key to the app and have the app not respond right away.
6175TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6176 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006178 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6179 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006180 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006181 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006182 ASSERT_TRUE(mDispatcher->waitForIdle());
6183}
6184
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006185// We have a focused application, but no focused window
6186TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006187 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6189 mWindow->consumeFocusEvent(false);
6190
6191 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006193 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6194 WINDOW_LOCATION));
6195 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6196 mDispatcher->waitForIdle();
6197 mFakePolicy->assertNotifyAnrWasNotCalled();
6198
6199 // Once a focused event arrives, we get an ANR for this application
6200 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6201 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006202 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006203 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6204 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006205 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006207 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 ASSERT_TRUE(mDispatcher->waitForIdle());
6209}
6210
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006211/**
6212 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6213 * there will not be an ANR.
6214 */
6215TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6216 mWindow->setFocusable(false);
6217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6218 mWindow->consumeFocusEvent(false);
6219
6220 KeyEvent event;
6221 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6222 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6223
6224 // Define a valid key down event that is stale (too old).
6225 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6226 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006227 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006228
6229 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6230
6231 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006232 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006233 InputEventInjectionSync::WAIT_FOR_RESULT,
6234 INJECT_EVENT_TIMEOUT, policyFlags);
6235 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6236 << "Injection should fail because the event is stale";
6237
6238 ASSERT_TRUE(mDispatcher->waitForIdle());
6239 mFakePolicy->assertNotifyAnrWasNotCalled();
6240 mWindow->assertNoEvents();
6241}
6242
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006243// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006244// Make sure that we don't notify policy twice about the same ANR.
6245TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006246 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6248 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006249
6250 // Once a focused event arrives, we get an ANR for this application
6251 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6252 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006253 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006254 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6255 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006256 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006257 const std::chrono::duration appTimeout =
6258 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6259 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006260
Vishnu Naire4df8752022-09-08 09:17:55 -07006261 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006262 // ANR should not be raised again. It is up to policy to do that if it desires.
6263 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006264
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006265 // If we now get a focused window, the ANR should stop, but the policy handles that via
6266 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006267 ASSERT_TRUE(mDispatcher->waitForIdle());
6268}
6269
6270// We have a focused application, but no focused window
6271TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006272 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6274 mWindow->consumeFocusEvent(false);
6275
6276 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006277 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006278 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006279 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6280 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006281
Vishnu Naire4df8752022-09-08 09:17:55 -07006282 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6283 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006284
6285 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006286 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006287 ASSERT_TRUE(mDispatcher->waitForIdle());
6288 mWindow->assertNoEvents();
6289}
6290
6291/**
6292 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6293 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6294 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6295 * the ANR mechanism should still work.
6296 *
6297 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6298 * DOWN event, while not responding on the second one.
6299 */
6300TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6301 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6302 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6303 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6304 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6305 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006306 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006307
6308 // Now send ACTION_UP, with identical timestamp
6309 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6310 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6311 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6312 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006313 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314
6315 // We have now sent down and up. Let's consume first event and then ANR on the second.
6316 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6317 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006318 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006319}
6320
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006321// A spy window can receive an ANR
6322TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6323 sp<FakeWindowHandle> spy = addSpyWindow();
6324
6325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6326 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6327 WINDOW_LOCATION));
6328 mWindow->consumeMotionDown();
6329
6330 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6331 ASSERT_TRUE(sequenceNum);
6332 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006333 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006334
6335 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006336 spy->consumeMotionEvent(
6337 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006338 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006339 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006340}
6341
6342// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006343// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006344TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6345 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6348 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006349 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006351
6352 // Stuck on the ACTION_UP
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
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006356 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006357 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006358 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6359 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006360
6361 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6362 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006363 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006364 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006365 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006366}
6367
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006368// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006369// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006370TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6371 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006372
6373 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006374 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6375 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006376
6377 mWindow->consumeMotionDown();
6378 // Stuck on the ACTION_UP
6379 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006380 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006381
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006382 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006384 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6385 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006386
6387 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6388 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006389 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006390 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006391 spy->assertNoEvents();
6392}
6393
6394TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6395 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6396
6397 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6398
6399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6400 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6401 WINDOW_LOCATION));
6402
6403 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6404 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6405 ASSERT_TRUE(consumeSeq);
6406
Prabir Pradhanedd96402022-02-15 01:46:16 -08006407 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006408
6409 monitor.finishEvent(*consumeSeq);
6410 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6411
6412 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006413 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006414}
6415
6416// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6417// process events, you don't get an anr. When the window later becomes unresponsive again, you
6418// get an ANR again.
6419// 1. tap -> block on ACTION_UP -> receive ANR
6420// 2. consume all pending events (= queue becomes healthy again)
6421// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6422TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6423 tapOnWindow();
6424
6425 mWindow->consumeMotionDown();
6426 // Block on ACTION_UP
6427 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006428 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006429 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6430 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006431 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006432 mWindow->assertNoEvents();
6433
6434 tapOnWindow();
6435 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006436 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006437 mWindow->consumeMotionUp();
6438
6439 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006440 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006441 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006442 mWindow->assertNoEvents();
6443}
6444
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006445// If a connection remains unresponsive for a while, make sure policy is only notified once about
6446// it.
6447TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6450 WINDOW_LOCATION));
6451
6452 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006453 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006454 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006455 // 'notifyConnectionUnresponsive' should only be called once per connection
6456 mFakePolicy->assertNotifyAnrWasNotCalled();
6457 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006458 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006459 mWindow->consumeMotionEvent(
6460 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006461 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006462 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006463 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006464 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006465}
6466
6467/**
6468 * If a window is processing a motion event, and then a key event comes in, the key event should
6469 * not to to the focused window until the motion is processed.
6470 *
6471 * Warning!!!
6472 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6473 * and the injection timeout that we specify when injecting the key.
6474 * We must have the injection timeout (10ms) be smaller than
6475 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6476 *
6477 * If that value changes, this test should also change.
6478 */
6479TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6480 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6482
6483 tapOnWindow();
6484 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6485 ASSERT_TRUE(downSequenceNum);
6486 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6487 ASSERT_TRUE(upSequenceNum);
6488 // Don't finish the events yet, and send a key
6489 // Injection will "succeed" because we will eventually give up and send the key to the focused
6490 // window even if motions are still being processed. But because the injection timeout is short,
6491 // we will receive INJECTION_TIMED_OUT as the result.
6492
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006493 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006494 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006495 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6496 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006497 // Key will not be sent to the window, yet, because the window is still processing events
6498 // and the key remains pending, waiting for the touch events to be processed
6499 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6500 ASSERT_FALSE(keySequenceNum);
6501
6502 std::this_thread::sleep_for(500ms);
6503 // if we wait long enough though, dispatcher will give up, and still send the key
6504 // to the focused window, even though we have not yet finished the motion event
6505 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6506 mWindow->finishEvent(*downSequenceNum);
6507 mWindow->finishEvent(*upSequenceNum);
6508}
6509
6510/**
6511 * If a window is processing a motion event, and then a key event comes in, the key event should
6512 * not go to the focused window until the motion is processed.
6513 * If then a new motion comes in, then the pending key event should be going to the currently
6514 * focused window right away.
6515 */
6516TEST_F(InputDispatcherSingleWindowAnr,
6517 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6518 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6520
6521 tapOnWindow();
6522 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6523 ASSERT_TRUE(downSequenceNum);
6524 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6525 ASSERT_TRUE(upSequenceNum);
6526 // Don't finish the events yet, and send a key
6527 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006529 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6530 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006531 // At this point, key is still pending, and should not be sent to the application yet.
6532 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6533 ASSERT_FALSE(keySequenceNum);
6534
6535 // Now tap down again. It should cause the pending key to go to the focused window right away.
6536 tapOnWindow();
6537 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6538 // the other events yet. We can finish events in any order.
6539 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6540 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6541 mWindow->consumeMotionDown();
6542 mWindow->consumeMotionUp();
6543 mWindow->assertNoEvents();
6544}
6545
6546class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6547 virtual void SetUp() override {
6548 InputDispatcherTest::SetUp();
6549
Chris Yea209fde2020-07-22 13:54:51 -07006550 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006551 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006552 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6553 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006554 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006555 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006556 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006557
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006558 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6559 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006560 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006561 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006562
6563 // Set focused application.
6564 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006565 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006566
6567 // Expect one focus window exist in display.
6568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006569 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006570 mFocusedWindow->consumeFocusEvent(true);
6571 }
6572
6573 virtual void TearDown() override {
6574 InputDispatcherTest::TearDown();
6575
6576 mUnfocusedWindow.clear();
6577 mFocusedWindow.clear();
6578 }
6579
6580protected:
Chris Yea209fde2020-07-22 13:54:51 -07006581 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006582 sp<FakeWindowHandle> mUnfocusedWindow;
6583 sp<FakeWindowHandle> mFocusedWindow;
6584 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6585 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6586 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6587
6588 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6589
6590 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6591
6592private:
6593 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6596 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006598 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6599 location));
6600 }
6601};
6602
6603// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6604// should be ANR'd first.
6605TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6608 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006610 mFocusedWindow->consumeMotionDown();
6611 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006612 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006613 // We consumed all events, so no ANR
6614 ASSERT_TRUE(mDispatcher->waitForIdle());
6615 mFakePolicy->assertNotifyAnrWasNotCalled();
6616
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6619 FOCUSED_WINDOW_LOCATION));
6620 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6621 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006622
6623 const std::chrono::duration timeout =
6624 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006625 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006626 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6627 // sequence to make it consistent
6628 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006629 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006630 mFocusedWindow->consumeMotionDown();
6631 // This cancel is generated because the connection was unresponsive
6632 mFocusedWindow->consumeMotionCancel();
6633 mFocusedWindow->assertNoEvents();
6634 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006635 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006636 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6637 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006638 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006639}
6640
6641// If we have 2 windows with identical timeouts that are both unresponsive,
6642// it doesn't matter which order they should have ANR.
6643// But we should receive ANR for both.
6644TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6645 // Set the timeout for unfocused window to match the focused window
6646 mUnfocusedWindow->setDispatchingTimeout(10ms);
6647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6648
6649 tapOnFocusedWindow();
6650 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006651 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6652 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6653 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006654
6655 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006656 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6657 mFocusedWindow->getToken() == anrConnectionToken2);
6658 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6659 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006660
6661 ASSERT_TRUE(mDispatcher->waitForIdle());
6662 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006663
6664 mFocusedWindow->consumeMotionDown();
6665 mFocusedWindow->consumeMotionUp();
6666 mUnfocusedWindow->consumeMotionOutside();
6667
Prabir Pradhanedd96402022-02-15 01:46:16 -08006668 sp<IBinder> responsiveToken1, responsiveToken2;
6669 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6670 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006671
6672 // Both applications should be marked as responsive, in any order
6673 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6674 mFocusedWindow->getToken() == responsiveToken2);
6675 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6676 mUnfocusedWindow->getToken() == responsiveToken2);
6677 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006678}
6679
6680// If a window is already not responding, the second tap on the same window should be ignored.
6681// We should also log an error to account for the dropped event (not tested here).
6682// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6683TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6684 tapOnFocusedWindow();
6685 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006686 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006687 // Receive the events, but don't respond
6688 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6689 ASSERT_TRUE(downEventSequenceNum);
6690 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6691 ASSERT_TRUE(upEventSequenceNum);
6692 const std::chrono::duration timeout =
6693 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006694 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006695
6696 // Tap once again
6697 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006698 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006699 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6700 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006701 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006702 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6703 FOCUSED_WINDOW_LOCATION));
6704 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6705 // valid touch target
6706 mUnfocusedWindow->assertNoEvents();
6707
6708 // Consume the first tap
6709 mFocusedWindow->finishEvent(*downEventSequenceNum);
6710 mFocusedWindow->finishEvent(*upEventSequenceNum);
6711 ASSERT_TRUE(mDispatcher->waitForIdle());
6712 // The second tap did not go to the focused window
6713 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006714 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006715 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6716 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006717 mFakePolicy->assertNotifyAnrWasNotCalled();
6718}
6719
6720// If you tap outside of all windows, there will not be ANR
6721TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006722 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6724 LOCATION_OUTSIDE_ALL_WINDOWS));
6725 ASSERT_TRUE(mDispatcher->waitForIdle());
6726 mFakePolicy->assertNotifyAnrWasNotCalled();
6727}
6728
6729// Since the focused window is paused, tapping on it should not produce any events
6730TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6731 mFocusedWindow->setPaused(true);
6732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6733
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));
6737
6738 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6739 ASSERT_TRUE(mDispatcher->waitForIdle());
6740 // Should not ANR because the window is paused, and touches shouldn't go to it
6741 mFakePolicy->assertNotifyAnrWasNotCalled();
6742
6743 mFocusedWindow->assertNoEvents();
6744 mUnfocusedWindow->assertNoEvents();
6745}
6746
6747/**
6748 * If a window is processing a motion event, and then a key event comes in, the key event should
6749 * not to to the focused window until the motion is processed.
6750 * If a different window becomes focused at this time, the key should go to that window instead.
6751 *
6752 * Warning!!!
6753 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6754 * and the injection timeout that we specify when injecting the key.
6755 * We must have the injection timeout (10ms) be smaller than
6756 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6757 *
6758 * If that value changes, this test should also change.
6759 */
6760TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6761 // Set a long ANR timeout to prevent it from triggering
6762 mFocusedWindow->setDispatchingTimeout(2s);
6763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6764
6765 tapOnUnfocusedWindow();
6766 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6767 ASSERT_TRUE(downSequenceNum);
6768 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6769 ASSERT_TRUE(upSequenceNum);
6770 // Don't finish the events yet, and send a key
6771 // Injection will succeed because we will eventually give up and send the key to the focused
6772 // window even if motions are still being processed.
6773
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006774 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006775 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6776 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006778 // Key will not be sent to the window, yet, because the window is still processing events
6779 // and the key remains pending, waiting for the touch events to be processed
6780 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6781 ASSERT_FALSE(keySequenceNum);
6782
6783 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006784 mFocusedWindow->setFocusable(false);
6785 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006787 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006788
6789 // Focus events should precede the key events
6790 mUnfocusedWindow->consumeFocusEvent(true);
6791 mFocusedWindow->consumeFocusEvent(false);
6792
6793 // Finish the tap events, which should unblock dispatcher
6794 mUnfocusedWindow->finishEvent(*downSequenceNum);
6795 mUnfocusedWindow->finishEvent(*upSequenceNum);
6796
6797 // Now that all queues are cleared and no backlog in the connections, the key event
6798 // can finally go to the newly focused "mUnfocusedWindow".
6799 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6800 mFocusedWindow->assertNoEvents();
6801 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006802 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006803}
6804
6805// When the touch stream is split across 2 windows, and one of them does not respond,
6806// then ANR should be raised and the touch should be canceled for the unresponsive window.
6807// The other window should not be affected by that.
6808TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6809 // Touch Window 1
6810 NotifyMotionArgs motionArgs =
6811 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6812 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6813 mDispatcher->notifyMotion(&motionArgs);
6814 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006815 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006816
6817 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006818 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6819 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006820 mDispatcher->notifyMotion(&motionArgs);
6821
6822 const std::chrono::duration timeout =
6823 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006824 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006825
6826 mUnfocusedWindow->consumeMotionDown();
6827 mFocusedWindow->consumeMotionDown();
6828 // Focused window may or may not receive ACTION_MOVE
6829 // But it should definitely receive ACTION_CANCEL due to the ANR
6830 InputEvent* event;
6831 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6832 ASSERT_TRUE(moveOrCancelSequenceNum);
6833 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6834 ASSERT_NE(nullptr, event);
6835 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6836 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6837 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6838 mFocusedWindow->consumeMotionCancel();
6839 } else {
6840 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6841 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006842 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006843 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6844 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006846 mUnfocusedWindow->assertNoEvents();
6847 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006848 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006849}
6850
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006851/**
6852 * If we have no focused window, and a key comes in, we start the ANR timer.
6853 * The focused application should add a focused window before the timer runs out to prevent ANR.
6854 *
6855 * If the user touches another application during this time, the key should be dropped.
6856 * Next, if a new focused window comes in, without toggling the focused application,
6857 * then no ANR should occur.
6858 *
6859 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6860 * but in some cases the policy may not update the focused application.
6861 */
6862TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6863 std::shared_ptr<FakeApplicationHandle> focusedApplication =
6864 std::make_shared<FakeApplicationHandle>();
6865 focusedApplication->setDispatchingTimeout(60ms);
6866 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
6867 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
6868 mFocusedWindow->setFocusable(false);
6869
6870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6871 mFocusedWindow->consumeFocusEvent(false);
6872
6873 // Send a key. The ANR timer should start because there is no focused window.
6874 // 'focusedApplication' will get blamed if this timer completes.
6875 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006876 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006877 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6878 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6879 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006881
6882 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
6883 // then the injected touches won't cause the focused event to get dropped.
6884 // The dispatcher only checks for whether the queue should be pruned upon queueing.
6885 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
6886 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
6887 // For this test, it means that the key would get delivered to the window once it becomes
6888 // focused.
6889 std::this_thread::sleep_for(10ms);
6890
6891 // Touch unfocused window. This should force the pending key to get dropped.
6892 NotifyMotionArgs motionArgs =
6893 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6894 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
6895 mDispatcher->notifyMotion(&motionArgs);
6896
6897 // We do not consume the motion right away, because that would require dispatcher to first
6898 // process (== drop) the key event, and by that time, ANR will be raised.
6899 // Set the focused window first.
6900 mFocusedWindow->setFocusable(true);
6901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6902 setFocusedWindow(mFocusedWindow);
6903 mFocusedWindow->consumeFocusEvent(true);
6904 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
6905 // to another application. This could be a bug / behaviour in the policy.
6906
6907 mUnfocusedWindow->consumeMotionDown();
6908
6909 ASSERT_TRUE(mDispatcher->waitForIdle());
6910 // Should not ANR because we actually have a focused window. It was just added too slowly.
6911 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
6912}
6913
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006914// These tests ensure we cannot send touch events to a window that's positioned behind a window
6915// that has feature NO_INPUT_CHANNEL.
6916// Layout:
6917// Top (closest to user)
6918// mNoInputWindow (above all windows)
6919// mBottomWindow
6920// Bottom (furthest from user)
6921class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
6922 virtual void SetUp() override {
6923 InputDispatcherTest::SetUp();
6924
6925 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006926 mNoInputWindow =
6927 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6928 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00006929 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006930 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006931 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6932 // It's perfectly valid for this window to not have an associated input channel
6933
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006934 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
6935 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006936 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
6937
6938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6939 }
6940
6941protected:
6942 std::shared_ptr<FakeApplicationHandle> mApplication;
6943 sp<FakeWindowHandle> mNoInputWindow;
6944 sp<FakeWindowHandle> mBottomWindow;
6945};
6946
6947TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
6948 PointF touchedPoint = {10, 10};
6949
6950 NotifyMotionArgs motionArgs =
6951 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6952 ADISPLAY_ID_DEFAULT, {touchedPoint});
6953 mDispatcher->notifyMotion(&motionArgs);
6954
6955 mNoInputWindow->assertNoEvents();
6956 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
6957 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
6958 // and therefore should prevent mBottomWindow from receiving touches
6959 mBottomWindow->assertNoEvents();
6960}
6961
6962/**
6963 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
6964 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
6965 */
6966TEST_F(InputDispatcherMultiWindowOcclusionTests,
6967 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006968 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6969 "Window with input channel and NO_INPUT_CHANNEL",
6970 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006971
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006972 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006973 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6975
6976 PointF touchedPoint = {10, 10};
6977
6978 NotifyMotionArgs motionArgs =
6979 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6980 ADISPLAY_ID_DEFAULT, {touchedPoint});
6981 mDispatcher->notifyMotion(&motionArgs);
6982
6983 mNoInputWindow->assertNoEvents();
6984 mBottomWindow->assertNoEvents();
6985}
6986
Vishnu Nair958da932020-08-21 17:12:37 -07006987class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
6988protected:
6989 std::shared_ptr<FakeApplicationHandle> mApp;
6990 sp<FakeWindowHandle> mWindow;
6991 sp<FakeWindowHandle> mMirror;
6992
6993 virtual void SetUp() override {
6994 InputDispatcherTest::SetUp();
6995 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006996 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6997 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
6998 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07006999 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7000 mWindow->setFocusable(true);
7001 mMirror->setFocusable(true);
7002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7003 }
7004};
7005
7006TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7007 // Request focus on a mirrored window
7008 setFocusedWindow(mMirror);
7009
7010 // window gets focused
7011 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7013 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007014 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7015}
7016
7017// A focused & mirrored window remains focused only if the window and its mirror are both
7018// focusable.
7019TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7020 setFocusedWindow(mMirror);
7021
7022 // window gets focused
7023 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7025 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007026 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7028 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007029 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7030
7031 mMirror->setFocusable(false);
7032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7033
7034 // window loses focus since one of the windows associated with the token in not focusable
7035 mWindow->consumeFocusEvent(false);
7036
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007037 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7038 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007039 mWindow->assertNoEvents();
7040}
7041
7042// A focused & mirrored window remains focused until the window and its mirror both become
7043// invisible.
7044TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7045 setFocusedWindow(mMirror);
7046
7047 // window gets focused
7048 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7050 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007051 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7053 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007054 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7055
7056 mMirror->setVisible(false);
7057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7058
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7060 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007061 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7063 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007064 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7065
7066 mWindow->setVisible(false);
7067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7068
7069 // window loses focus only after all windows associated with the token become invisible.
7070 mWindow->consumeFocusEvent(false);
7071
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007072 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7073 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007074 mWindow->assertNoEvents();
7075}
7076
7077// A focused & mirrored window remains focused until both windows are removed.
7078TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7079 setFocusedWindow(mMirror);
7080
7081 // window gets focused
7082 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7084 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007085 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7087 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007088 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7089
7090 // single window is removed but the window token remains focused
7091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7092
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7094 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007095 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7097 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007098 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7099
7100 // Both windows are removed
7101 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7102 mWindow->consumeFocusEvent(false);
7103
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007104 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7105 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007106 mWindow->assertNoEvents();
7107}
7108
7109// Focus request can be pending until one window becomes visible.
7110TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7111 // Request focus on an invisible mirror.
7112 mWindow->setVisible(false);
7113 mMirror->setVisible(false);
7114 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7115 setFocusedWindow(mMirror);
7116
7117 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007119 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7120 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007121
7122 mMirror->setVisible(true);
7123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7124
7125 // window gets focused
7126 mWindow->consumeFocusEvent(true);
7127 // window gets the pending key event
7128 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7129}
Prabir Pradhan99987712020-11-10 18:43:05 -08007130
7131class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7132protected:
7133 std::shared_ptr<FakeApplicationHandle> mApp;
7134 sp<FakeWindowHandle> mWindow;
7135 sp<FakeWindowHandle> mSecondWindow;
7136
7137 void SetUp() override {
7138 InputDispatcherTest::SetUp();
7139 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007140 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007141 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007142 mSecondWindow =
7143 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007144 mSecondWindow->setFocusable(true);
7145
7146 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7148
7149 setFocusedWindow(mWindow);
7150 mWindow->consumeFocusEvent(true);
7151 }
7152
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007153 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7154 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007155 mDispatcher->notifyPointerCaptureChanged(&args);
7156 }
7157
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007158 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7159 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007160 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007161 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7162 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007163 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007164 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007165 }
7166};
7167
7168TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7169 // Ensure that capture cannot be obtained for unfocused windows.
7170 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7171 mFakePolicy->assertSetPointerCaptureNotCalled();
7172 mSecondWindow->assertNoEvents();
7173
7174 // Ensure that capture can be enabled from the focus window.
7175 requestAndVerifyPointerCapture(mWindow, true);
7176
7177 // Ensure that capture cannot be disabled from a window that does not have capture.
7178 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7179 mFakePolicy->assertSetPointerCaptureNotCalled();
7180
7181 // Ensure that capture can be disabled from the window with capture.
7182 requestAndVerifyPointerCapture(mWindow, false);
7183}
7184
7185TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007186 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007187
7188 setFocusedWindow(mSecondWindow);
7189
7190 // Ensure that the capture disabled event was sent first.
7191 mWindow->consumeCaptureEvent(false);
7192 mWindow->consumeFocusEvent(false);
7193 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007194 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007195
7196 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007197 notifyPointerCaptureChanged({});
7198 notifyPointerCaptureChanged(request);
7199 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007200 mWindow->assertNoEvents();
7201 mSecondWindow->assertNoEvents();
7202 mFakePolicy->assertSetPointerCaptureNotCalled();
7203}
7204
7205TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007206 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007207
7208 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007209 notifyPointerCaptureChanged({});
7210 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007211
7212 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007213 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007214 mWindow->consumeCaptureEvent(false);
7215 mWindow->assertNoEvents();
7216}
7217
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007218TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7219 requestAndVerifyPointerCapture(mWindow, true);
7220
7221 // The first window loses focus.
7222 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007223 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007224 mWindow->consumeCaptureEvent(false);
7225
7226 // Request Pointer Capture from the second window before the notification from InputReader
7227 // arrives.
7228 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007229 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007230
7231 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007232 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007233
7234 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007235 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007236
7237 mSecondWindow->consumeFocusEvent(true);
7238 mSecondWindow->consumeCaptureEvent(true);
7239}
7240
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007241TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7242 // App repeatedly enables and disables capture.
7243 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7244 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7245 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7246 mFakePolicy->assertSetPointerCaptureCalled(false);
7247 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7248 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7249
7250 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7251 // first request is now stale, this should do nothing.
7252 notifyPointerCaptureChanged(firstRequest);
7253 mWindow->assertNoEvents();
7254
7255 // InputReader notifies that the second request was enabled.
7256 notifyPointerCaptureChanged(secondRequest);
7257 mWindow->consumeCaptureEvent(true);
7258}
7259
Prabir Pradhan7092e262022-05-03 16:51:09 +00007260TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7261 requestAndVerifyPointerCapture(mWindow, true);
7262
7263 // App toggles pointer capture off and on.
7264 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7265 mFakePolicy->assertSetPointerCaptureCalled(false);
7266
7267 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7268 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7269
7270 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7271 // preceding "disable" request.
7272 notifyPointerCaptureChanged(enableRequest);
7273
7274 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7275 // any notifications.
7276 mWindow->assertNoEvents();
7277}
7278
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007279class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7280protected:
7281 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007282
7283 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7284 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7285
7286 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7287 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7288
7289 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7290 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7291 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7292 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7293 MAXIMUM_OBSCURING_OPACITY);
7294
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007295 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007296 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007297 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007298
7299 sp<FakeWindowHandle> mTouchWindow;
7300
7301 virtual void SetUp() override {
7302 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007303 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007304 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7305 }
7306
7307 virtual void TearDown() override {
7308 InputDispatcherTest::TearDown();
7309 mTouchWindow.clear();
7310 }
7311
chaviw3277faf2021-05-19 16:45:23 -05007312 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7313 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007314 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007315 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007316 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007317 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007318 return window;
7319 }
7320
7321 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7322 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7323 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007324 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007325 // Generate an arbitrary PID based on the UID
7326 window->setOwnerInfo(1777 + (uid % 10000), uid);
7327 return window;
7328 }
7329
7330 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7331 NotifyMotionArgs args =
7332 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7333 ADISPLAY_ID_DEFAULT, points);
7334 mDispatcher->notifyMotion(&args);
7335 }
7336};
7337
7338TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007339 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007340 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007342
7343 touch();
7344
7345 mTouchWindow->assertNoEvents();
7346}
7347
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007348TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007349 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7350 const sp<FakeWindowHandle>& w =
7351 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7353
7354 touch();
7355
7356 mTouchWindow->assertNoEvents();
7357}
7358
7359TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007360 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7361 const sp<FakeWindowHandle>& w =
7362 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7364
7365 touch();
7366
7367 w->assertNoEvents();
7368}
7369
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007370TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007371 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007373
7374 touch();
7375
7376 mTouchWindow->consumeAnyMotionDown();
7377}
7378
7379TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007380 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007381 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007382 w->setFrame(Rect(0, 0, 50, 50));
7383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007384
7385 touch({PointF{100, 100}});
7386
7387 mTouchWindow->consumeAnyMotionDown();
7388}
7389
7390TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007391 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007392 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7394
7395 touch();
7396
7397 mTouchWindow->consumeAnyMotionDown();
7398}
7399
7400TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7401 const sp<FakeWindowHandle>& w =
7402 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007404
7405 touch();
7406
7407 mTouchWindow->consumeAnyMotionDown();
7408}
7409
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007410TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7411 const sp<FakeWindowHandle>& w =
7412 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7414
7415 touch();
7416
7417 w->assertNoEvents();
7418}
7419
7420/**
7421 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7422 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7423 * window, the occluding window will still receive ACTION_OUTSIDE event.
7424 */
7425TEST_F(InputDispatcherUntrustedTouchesTest,
7426 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7427 const sp<FakeWindowHandle>& w =
7428 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007429 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007430 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7431
7432 touch();
7433
7434 w->consumeMotionOutside();
7435}
7436
7437TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7438 const sp<FakeWindowHandle>& w =
7439 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007440 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007441 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7442
7443 touch();
7444
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007445 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007446}
7447
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007448TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007449 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007450 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7451 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7453
7454 touch();
7455
7456 mTouchWindow->consumeAnyMotionDown();
7457}
7458
7459TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7460 const sp<FakeWindowHandle>& w =
7461 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7462 MAXIMUM_OBSCURING_OPACITY);
7463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007464
7465 touch();
7466
7467 mTouchWindow->consumeAnyMotionDown();
7468}
7469
7470TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007471 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007472 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7473 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007474 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7475
7476 touch();
7477
7478 mTouchWindow->assertNoEvents();
7479}
7480
7481TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7482 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7483 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007484 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7485 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007486 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007487 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7488 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7490
7491 touch();
7492
7493 mTouchWindow->assertNoEvents();
7494}
7495
7496TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7497 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7498 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007499 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7500 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007501 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007502 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7503 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7505
7506 touch();
7507
7508 mTouchWindow->consumeAnyMotionDown();
7509}
7510
7511TEST_F(InputDispatcherUntrustedTouchesTest,
7512 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7513 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007514 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7515 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007516 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007517 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7518 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7520
7521 touch();
7522
7523 mTouchWindow->consumeAnyMotionDown();
7524}
7525
7526TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7527 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007528 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7529 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007530 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007531 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7532 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007534
7535 touch();
7536
7537 mTouchWindow->assertNoEvents();
7538}
7539
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007540TEST_F(InputDispatcherUntrustedTouchesTest,
7541 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7542 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007543 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7544 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007545 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007546 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7547 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7549
7550 touch();
7551
7552 mTouchWindow->assertNoEvents();
7553}
7554
7555TEST_F(InputDispatcherUntrustedTouchesTest,
7556 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7557 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007558 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7559 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007560 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007561 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7562 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7564
7565 touch();
7566
7567 mTouchWindow->consumeAnyMotionDown();
7568}
7569
7570TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7571 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007572 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7573 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7575
7576 touch();
7577
7578 mTouchWindow->consumeAnyMotionDown();
7579}
7580
7581TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7582 const sp<FakeWindowHandle>& w =
7583 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7585
7586 touch();
7587
7588 mTouchWindow->consumeAnyMotionDown();
7589}
7590
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007591TEST_F(InputDispatcherUntrustedTouchesTest,
7592 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7593 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7594 const sp<FakeWindowHandle>& w =
7595 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7597
7598 touch();
7599
7600 mTouchWindow->assertNoEvents();
7601}
7602
7603TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7604 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7605 const sp<FakeWindowHandle>& w =
7606 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7608
7609 touch();
7610
7611 mTouchWindow->consumeAnyMotionDown();
7612}
7613
7614TEST_F(InputDispatcherUntrustedTouchesTest,
7615 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7616 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7617 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007618 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7619 OPACITY_ABOVE_THRESHOLD);
7620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7621
7622 touch();
7623
7624 mTouchWindow->consumeAnyMotionDown();
7625}
7626
7627TEST_F(InputDispatcherUntrustedTouchesTest,
7628 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7629 const sp<FakeWindowHandle>& w1 =
7630 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7631 OPACITY_BELOW_THRESHOLD);
7632 const sp<FakeWindowHandle>& w2 =
7633 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7634 OPACITY_BELOW_THRESHOLD);
7635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7636
7637 touch();
7638
7639 mTouchWindow->assertNoEvents();
7640}
7641
7642/**
7643 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7644 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7645 * (which alone would result in allowing touches) does not affect the blocking behavior.
7646 */
7647TEST_F(InputDispatcherUntrustedTouchesTest,
7648 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7649 const sp<FakeWindowHandle>& wB =
7650 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7651 OPACITY_BELOW_THRESHOLD);
7652 const sp<FakeWindowHandle>& wC =
7653 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7654 OPACITY_BELOW_THRESHOLD);
7655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7656
7657 touch();
7658
7659 mTouchWindow->assertNoEvents();
7660}
7661
7662/**
7663 * This test is testing that a window from a different UID but with same application token doesn't
7664 * block the touch. Apps can share the application token for close UI collaboration for example.
7665 */
7666TEST_F(InputDispatcherUntrustedTouchesTest,
7667 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7668 const sp<FakeWindowHandle>& w =
7669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7670 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7672
7673 touch();
7674
7675 mTouchWindow->consumeAnyMotionDown();
7676}
7677
arthurhungb89ccb02020-12-30 16:19:01 +08007678class InputDispatcherDragTests : public InputDispatcherTest {
7679protected:
7680 std::shared_ptr<FakeApplicationHandle> mApp;
7681 sp<FakeWindowHandle> mWindow;
7682 sp<FakeWindowHandle> mSecondWindow;
7683 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007684 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007685 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7686 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007687
7688 void SetUp() override {
7689 InputDispatcherTest::SetUp();
7690 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007691 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007692 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007693
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007694 mSecondWindow =
7695 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007696 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007697
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007698 mSpyWindow =
7699 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007700 mSpyWindow->setSpy(true);
7701 mSpyWindow->setTrustedOverlay(true);
7702 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7703
arthurhungb89ccb02020-12-30 16:19:01 +08007704 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007706 }
7707
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007708 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7709 switch (fromSource) {
7710 case AINPUT_SOURCE_TOUCHSCREEN:
7711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7713 ADISPLAY_ID_DEFAULT, {50, 50}))
7714 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7715 break;
7716 case AINPUT_SOURCE_STYLUS:
7717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7718 injectMotionEvent(
7719 mDispatcher,
7720 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7721 AINPUT_SOURCE_STYLUS)
7722 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7723 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7724 .x(50)
7725 .y(50))
7726 .build()));
7727 break;
7728 case AINPUT_SOURCE_MOUSE:
7729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7730 injectMotionEvent(
7731 mDispatcher,
7732 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7733 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7734 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7735 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7736 .x(50)
7737 .y(50))
7738 .build()));
7739 break;
7740 default:
7741 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7742 }
arthurhungb89ccb02020-12-30 16:19:01 +08007743
7744 // Window should receive motion event.
7745 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007746 // Spy window should also receive motion event
7747 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007748 }
7749
7750 // Start performing drag, we will create a drag window and transfer touch to it.
7751 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7752 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007753 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007754 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007755 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007756 }
arthurhungb89ccb02020-12-30 16:19:01 +08007757
7758 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007759 mDragWindow =
7760 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007761 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007762 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007763 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007764
7765 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007766 bool transferred =
7767 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007768 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007769 if (transferred) {
7770 mWindow->consumeMotionCancel();
7771 mDragWindow->consumeMotionDown();
7772 }
7773 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007774 }
7775};
7776
7777TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007778 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007779
7780 // Move on window.
7781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7782 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7783 ADISPLAY_ID_DEFAULT, {50, 50}))
7784 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7785 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7786 mWindow->consumeDragEvent(false, 50, 50);
7787 mSecondWindow->assertNoEvents();
7788
7789 // Move to another window.
7790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7791 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7792 ADISPLAY_ID_DEFAULT, {150, 50}))
7793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7794 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7795 mWindow->consumeDragEvent(true, 150, 50);
7796 mSecondWindow->consumeDragEvent(false, 50, 50);
7797
7798 // Move back to original window.
7799 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7800 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7801 ADISPLAY_ID_DEFAULT, {50, 50}))
7802 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7803 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7804 mWindow->consumeDragEvent(false, 50, 50);
7805 mSecondWindow->consumeDragEvent(true, -50, 50);
7806
7807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7808 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7810 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7811 mWindow->assertNoEvents();
7812 mSecondWindow->assertNoEvents();
7813}
7814
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007815TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007816 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007817
7818 // No cancel event after drag start
7819 mSpyWindow->assertNoEvents();
7820
7821 const MotionEvent secondFingerDownEvent =
7822 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7823 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007824 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7825 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007826 .build();
7827 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7828 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7829 InputEventInjectionSync::WAIT_FOR_RESULT))
7830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7831
7832 // Receives cancel for first pointer after next pointer down
7833 mSpyWindow->consumeMotionCancel();
7834 mSpyWindow->consumeMotionDown();
7835
7836 mSpyWindow->assertNoEvents();
7837}
7838
arthurhungf452d0b2021-01-06 00:19:52 +08007839TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007840 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007841
7842 // Move on window.
7843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7844 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7845 ADISPLAY_ID_DEFAULT, {50, 50}))
7846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7847 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7848 mWindow->consumeDragEvent(false, 50, 50);
7849 mSecondWindow->assertNoEvents();
7850
7851 // Move to another window.
7852 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7853 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7854 ADISPLAY_ID_DEFAULT, {150, 50}))
7855 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7856 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7857 mWindow->consumeDragEvent(true, 150, 50);
7858 mSecondWindow->consumeDragEvent(false, 50, 50);
7859
7860 // drop to another window.
7861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7862 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7863 {150, 50}))
7864 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7865 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7866 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7867 mWindow->assertNoEvents();
7868 mSecondWindow->assertNoEvents();
7869}
7870
arthurhung6d4bed92021-03-17 11:59:33 +08007871TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007872 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08007873
7874 // Move on window and keep button pressed.
7875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7876 injectMotionEvent(mDispatcher,
7877 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7878 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7879 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7880 .x(50)
7881 .y(50))
7882 .build()))
7883 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7884 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7885 mWindow->consumeDragEvent(false, 50, 50);
7886 mSecondWindow->assertNoEvents();
7887
7888 // Move to another window and release button, expect to drop item.
7889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7890 injectMotionEvent(mDispatcher,
7891 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7892 .buttonState(0)
7893 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7894 .x(150)
7895 .y(50))
7896 .build()))
7897 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7898 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7899 mWindow->assertNoEvents();
7900 mSecondWindow->assertNoEvents();
7901 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7902
7903 // nothing to the window.
7904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7905 injectMotionEvent(mDispatcher,
7906 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
7907 .buttonState(0)
7908 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7909 .x(150)
7910 .y(50))
7911 .build()))
7912 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7913 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7914 mWindow->assertNoEvents();
7915 mSecondWindow->assertNoEvents();
7916}
7917
Arthur Hung54745652022-04-20 07:17:41 +00007918TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007919 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08007920
7921 // Set second window invisible.
7922 mSecondWindow->setVisible(false);
7923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
7924
7925 // Move on window.
7926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7927 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7928 ADISPLAY_ID_DEFAULT, {50, 50}))
7929 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7930 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7931 mWindow->consumeDragEvent(false, 50, 50);
7932 mSecondWindow->assertNoEvents();
7933
7934 // Move to another window.
7935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7936 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7937 ADISPLAY_ID_DEFAULT, {150, 50}))
7938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7939 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7940 mWindow->consumeDragEvent(true, 150, 50);
7941 mSecondWindow->assertNoEvents();
7942
7943 // drop to another window.
7944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7945 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7946 {150, 50}))
7947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7948 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7949 mFakePolicy->assertDropTargetEquals(nullptr);
7950 mWindow->assertNoEvents();
7951 mSecondWindow->assertNoEvents();
7952}
7953
Arthur Hung54745652022-04-20 07:17:41 +00007954TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007955 // Ensure window could track pointerIds if it didn't support split touch.
7956 mWindow->setPreventSplitting(true);
7957
Arthur Hung54745652022-04-20 07:17:41 +00007958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7960 {50, 50}))
7961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7962 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7963
7964 const MotionEvent secondFingerDownEvent =
7965 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7966 .displayId(ADISPLAY_ID_DEFAULT)
7967 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007968 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7969 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007970 .build();
7971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7972 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7973 InputEventInjectionSync::WAIT_FOR_RESULT))
7974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00007975 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00007976
7977 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007978 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007979}
7980
7981TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
7982 // First down on second window.
7983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7984 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7985 {150, 50}))
7986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7987
7988 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7989
7990 // Second down on first window.
7991 const MotionEvent secondFingerDownEvent =
7992 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7993 .displayId(ADISPLAY_ID_DEFAULT)
7994 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007995 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7996 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007997 .build();
7998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7999 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8000 InputEventInjectionSync::WAIT_FOR_RESULT))
8001 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8002 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8003
8004 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008005 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008006
8007 // Move on window.
8008 const MotionEvent secondFingerMoveEvent =
8009 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8010 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008011 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8012 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008013 .build();
8014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8015 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8016 InputEventInjectionSync::WAIT_FOR_RESULT));
8017 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8018 mWindow->consumeDragEvent(false, 50, 50);
8019 mSecondWindow->consumeMotionMove();
8020
8021 // Release the drag pointer should perform drop.
8022 const MotionEvent secondFingerUpEvent =
8023 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8024 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008025 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8026 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008027 .build();
8028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8029 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8030 InputEventInjectionSync::WAIT_FOR_RESULT));
8031 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8032 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8033 mWindow->assertNoEvents();
8034 mSecondWindow->consumeMotionMove();
8035}
8036
Arthur Hung3915c1f2022-05-31 07:17:17 +00008037TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008038 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008039
8040 // Update window of second display.
8041 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008042 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008043 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8044
8045 // Let second display has a touch state.
8046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8047 injectMotionEvent(mDispatcher,
8048 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8049 AINPUT_SOURCE_TOUCHSCREEN)
8050 .displayId(SECOND_DISPLAY_ID)
8051 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8052 .x(100)
8053 .y(100))
8054 .build()));
8055 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008056 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008057 // Update window again.
8058 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8059
8060 // Move on window.
8061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8062 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8063 ADISPLAY_ID_DEFAULT, {50, 50}))
8064 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8065 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8066 mWindow->consumeDragEvent(false, 50, 50);
8067 mSecondWindow->assertNoEvents();
8068
8069 // Move to another window.
8070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8071 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8072 ADISPLAY_ID_DEFAULT, {150, 50}))
8073 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8074 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8075 mWindow->consumeDragEvent(true, 150, 50);
8076 mSecondWindow->consumeDragEvent(false, 50, 50);
8077
8078 // drop to another window.
8079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8080 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8081 {150, 50}))
8082 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8083 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8084 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8085 mWindow->assertNoEvents();
8086 mSecondWindow->assertNoEvents();
8087}
8088
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008089TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8090 startDrag(true, AINPUT_SOURCE_MOUSE);
8091 // Move on window.
8092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8093 injectMotionEvent(mDispatcher,
8094 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8095 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8096 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8097 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8098 .x(50)
8099 .y(50))
8100 .build()))
8101 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8102 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8103 mWindow->consumeDragEvent(false, 50, 50);
8104 mSecondWindow->assertNoEvents();
8105
8106 // Move to another window.
8107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8108 injectMotionEvent(mDispatcher,
8109 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8110 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8111 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8112 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8113 .x(150)
8114 .y(50))
8115 .build()))
8116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8117 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8118 mWindow->consumeDragEvent(true, 150, 50);
8119 mSecondWindow->consumeDragEvent(false, 50, 50);
8120
8121 // drop to another window.
8122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8123 injectMotionEvent(mDispatcher,
8124 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8125 .buttonState(0)
8126 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8127 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8128 .x(150)
8129 .y(50))
8130 .build()))
8131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8132 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8133 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8134 mWindow->assertNoEvents();
8135 mSecondWindow->assertNoEvents();
8136}
8137
Vishnu Nair062a8672021-09-03 16:07:44 -07008138class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8139
8140TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8141 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008142 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8143 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008144 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008145 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8146 window->setFocusable(true);
8147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8148 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008149 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008150
8151 // With the flag set, window should not get any input
8152 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8153 mDispatcher->notifyKey(&keyArgs);
8154 window->assertNoEvents();
8155
8156 NotifyMotionArgs motionArgs =
8157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8158 ADISPLAY_ID_DEFAULT);
8159 mDispatcher->notifyMotion(&motionArgs);
8160 window->assertNoEvents();
8161
8162 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008163 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8165
8166 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8167 mDispatcher->notifyKey(&keyArgs);
8168 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8169
8170 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8171 ADISPLAY_ID_DEFAULT);
8172 mDispatcher->notifyMotion(&motionArgs);
8173 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8174 window->assertNoEvents();
8175}
8176
8177TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8178 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8179 std::make_shared<FakeApplicationHandle>();
8180 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008181 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8182 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008183 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8184 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008185 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008186 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008187 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8188 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008189 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008190 window->setOwnerInfo(222, 222);
8191 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8192 window->setFocusable(true);
8193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8194 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008195 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008196
8197 // With the flag set, window should not get any input
8198 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8199 mDispatcher->notifyKey(&keyArgs);
8200 window->assertNoEvents();
8201
8202 NotifyMotionArgs motionArgs =
8203 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8204 ADISPLAY_ID_DEFAULT);
8205 mDispatcher->notifyMotion(&motionArgs);
8206 window->assertNoEvents();
8207
8208 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008209 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8211
8212 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8213 mDispatcher->notifyKey(&keyArgs);
8214 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8215
8216 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8217 ADISPLAY_ID_DEFAULT);
8218 mDispatcher->notifyMotion(&motionArgs);
8219 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8220 window->assertNoEvents();
8221}
8222
8223TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8224 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8225 std::make_shared<FakeApplicationHandle>();
8226 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008227 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8228 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008229 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8230 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008231 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008232 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008233 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8234 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008235 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008236 window->setOwnerInfo(222, 222);
8237 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8238 window->setFocusable(true);
8239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8240 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008241 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008242
8243 // With the flag set, window should not get any input
8244 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8245 mDispatcher->notifyKey(&keyArgs);
8246 window->assertNoEvents();
8247
8248 NotifyMotionArgs motionArgs =
8249 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8250 ADISPLAY_ID_DEFAULT);
8251 mDispatcher->notifyMotion(&motionArgs);
8252 window->assertNoEvents();
8253
8254 // When the window is no longer obscured because it went on top, it should get input
8255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8256
8257 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8258 mDispatcher->notifyKey(&keyArgs);
8259 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8260
8261 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8262 ADISPLAY_ID_DEFAULT);
8263 mDispatcher->notifyMotion(&motionArgs);
8264 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8265 window->assertNoEvents();
8266}
8267
Antonio Kantekf16f2832021-09-28 04:39:20 +00008268class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8269protected:
8270 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008271 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008272 sp<FakeWindowHandle> mWindow;
8273 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008274 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008275
8276 void SetUp() override {
8277 InputDispatcherTest::SetUp();
8278
8279 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008280 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008281 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008282 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008283 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008284 mSecondWindow =
8285 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008286 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008287 mThirdWindow =
8288 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8289 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8290 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008291
8292 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8294 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8295 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008296 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008297
Antonio Kantek15beb512022-06-13 22:35:41 +00008298 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008299 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008300 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008301 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8302 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008303 mThirdWindow->assertNoEvents();
8304 }
8305
8306 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8307 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008308 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008309 SECOND_DISPLAY_ID)) {
8310 mWindow->assertNoEvents();
8311 mSecondWindow->assertNoEvents();
8312 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008313 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008314 }
8315
Antonio Kantek15beb512022-06-13 22:35:41 +00008316 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8317 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008318 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8319 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008320 mWindow->consumeTouchModeEvent(inTouchMode);
8321 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008322 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008323 }
8324};
8325
Antonio Kantek26defcf2022-02-08 01:12:27 +00008326TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008327 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008328 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8329 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008330 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008331}
8332
Antonio Kantek26defcf2022-02-08 01:12:27 +00008333TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8334 const WindowInfo& windowInfo = *mWindow->getInfo();
8335 int32_t ownerPid = windowInfo.ownerPid;
8336 int32_t ownerUid = windowInfo.ownerUid;
8337 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8338 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008339 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008340 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008341 mWindow->assertNoEvents();
8342 mSecondWindow->assertNoEvents();
8343}
8344
8345TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8346 const WindowInfo& windowInfo = *mWindow->getInfo();
8347 int32_t ownerPid = windowInfo.ownerPid;
8348 int32_t ownerUid = windowInfo.ownerUid;
8349 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008350 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008351 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008352}
8353
Antonio Kantekf16f2832021-09-28 04:39:20 +00008354TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008355 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008356 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8357 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008358 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008359 mWindow->assertNoEvents();
8360 mSecondWindow->assertNoEvents();
8361}
8362
Antonio Kantek15beb512022-06-13 22:35:41 +00008363TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8364 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8365 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8366 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008367 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008368 mWindow->assertNoEvents();
8369 mSecondWindow->assertNoEvents();
8370 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8371}
8372
Antonio Kantek48710e42022-03-24 14:19:30 -07008373TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8374 // Interact with the window first.
8375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8376 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8377 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8378
8379 // Then remove focus.
8380 mWindow->setFocusable(false);
8381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8382
8383 // Assert that caller can switch touch mode by owning one of the last interacted window.
8384 const WindowInfo& windowInfo = *mWindow->getInfo();
8385 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8386 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008387 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008388}
8389
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008390class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8391public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008392 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008393 std::shared_ptr<FakeApplicationHandle> application =
8394 std::make_shared<FakeApplicationHandle>();
8395 std::string name = "Fake Spy ";
8396 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008397 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8398 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008399 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008400 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008401 return spy;
8402 }
8403
8404 sp<FakeWindowHandle> createForeground() {
8405 std::shared_ptr<FakeApplicationHandle> application =
8406 std::make_shared<FakeApplicationHandle>();
8407 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008408 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8409 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008410 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008411 return window;
8412 }
8413
8414private:
8415 int mSpyCount{0};
8416};
8417
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008418using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008419/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008420 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8421 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008422TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8423 ScopedSilentDeath _silentDeath;
8424
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008425 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008426 spy->setTrustedOverlay(false);
8427 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8428 ".* not a trusted overlay");
8429}
8430
8431/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008432 * Input injection into a display with a spy window but no foreground windows should succeed.
8433 */
8434TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008435 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8437
8438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8439 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8440 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8441 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8442}
8443
8444/**
8445 * Verify the order in which different input windows receive events. The touched foreground window
8446 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8447 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8448 * receive events before ones belows it.
8449 *
8450 * Here, we set up a scenario with four windows in the following Z order from the top:
8451 * spy1, spy2, window, spy3.
8452 * We then inject an event and verify that the foreground "window" receives it first, followed by
8453 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8454 * window.
8455 */
8456TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8457 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008458 auto spy1 = createSpy();
8459 auto spy2 = createSpy();
8460 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8462 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8463 const size_t numChannels = channels.size();
8464
Michael Wright8e9a8562022-02-09 13:44:29 +00008465 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008466 if (!epollFd.ok()) {
8467 FAIL() << "Failed to create epoll fd";
8468 }
8469
8470 for (size_t i = 0; i < numChannels; i++) {
8471 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8472 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8473 FAIL() << "Failed to add fd to epoll";
8474 }
8475 }
8476
8477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8478 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8479 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8480
8481 std::vector<size_t> eventOrder;
8482 std::vector<struct epoll_event> events(numChannels);
8483 for (;;) {
8484 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8485 (100ms).count());
8486 if (nFds < 0) {
8487 FAIL() << "Failed to call epoll_wait";
8488 }
8489 if (nFds == 0) {
8490 break; // epoll_wait timed out
8491 }
8492 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008493 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008494 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008495 channels[i]->consumeMotionDown();
8496 }
8497 }
8498
8499 // Verify the order in which the events were received.
8500 EXPECT_EQ(3u, eventOrder.size());
8501 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8502 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8503 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8504}
8505
8506/**
8507 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8508 */
8509TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8510 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008511 auto spy = createSpy();
8512 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8514
8515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8518 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8519 spy->assertNoEvents();
8520}
8521
8522/**
8523 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8524 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8525 * to the window.
8526 */
8527TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8528 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008529 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008530 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8532
8533 // Inject an event outside the spy window's touchable region.
8534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8535 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8536 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8537 window->consumeMotionDown();
8538 spy->assertNoEvents();
8539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8540 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8542 window->consumeMotionUp();
8543 spy->assertNoEvents();
8544
8545 // Inject an event inside the spy window's touchable region.
8546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8548 {5, 10}))
8549 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8550 window->consumeMotionDown();
8551 spy->consumeMotionDown();
8552}
8553
8554/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008555 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008556 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008557 */
8558TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8559 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008560 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008561 auto spy = createSpy();
8562 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008563 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008564 spy->setFrame(Rect{0, 0, 20, 20});
8565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8566
8567 // Inject an event outside the spy window's frame and touchable region.
8568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008569 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8570 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8572 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008573 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008574}
8575
8576/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008577 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8578 * pointers that are down within its bounds.
8579 */
8580TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8581 auto windowLeft = createForeground();
8582 windowLeft->setFrame({0, 0, 100, 200});
8583 auto windowRight = createForeground();
8584 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008585 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008586 spy->setFrame({0, 0, 200, 200});
8587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8588
8589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8591 {50, 50}))
8592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8593 windowLeft->consumeMotionDown();
8594 spy->consumeMotionDown();
8595
8596 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008597 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008598 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008599 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8600 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008601 .build();
8602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8603 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8604 InputEventInjectionSync::WAIT_FOR_RESULT))
8605 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8606 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008607 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008608}
8609
8610/**
8611 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8612 * the spy should receive the second pointer with ACTION_DOWN.
8613 */
8614TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8615 auto window = createForeground();
8616 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008617 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008618 spyRight->setFrame({100, 0, 200, 200});
8619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8620
8621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8622 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8623 {50, 50}))
8624 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8625 window->consumeMotionDown();
8626 spyRight->assertNoEvents();
8627
8628 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008629 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008630 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008631 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8632 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008633 .build();
8634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8635 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8636 InputEventInjectionSync::WAIT_FOR_RESULT))
8637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008638 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008639 spyRight->consumeMotionDown();
8640}
8641
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008642/**
8643 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8644 * windows should be allowed to control split touch.
8645 */
8646TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008647 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008648 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008649 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008650 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008651
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008652 auto window = createForeground();
8653 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008654
8655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8656
8657 // First finger down, no window touched.
8658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8659 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8660 {100, 200}))
8661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8662 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8663 window->assertNoEvents();
8664
8665 // Second finger down on window, the window should receive touch down.
8666 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008667 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008668 .displayId(ADISPLAY_ID_DEFAULT)
8669 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008670 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8671 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008672 .build();
8673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8674 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8675 InputEventInjectionSync::WAIT_FOR_RESULT))
8676 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8677
8678 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008679 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008680}
8681
8682/**
8683 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8684 * do not receive key events.
8685 */
8686TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008687 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008688 spy->setFocusable(false);
8689
8690 auto window = createForeground();
8691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8692 setFocusedWindow(window);
8693 window->consumeFocusEvent(true);
8694
8695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8696 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8697 window->consumeKeyDown(ADISPLAY_ID_NONE);
8698
8699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8700 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8701 window->consumeKeyUp(ADISPLAY_ID_NONE);
8702
8703 spy->assertNoEvents();
8704}
8705
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008706using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8707
8708/**
8709 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8710 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8711 */
8712TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8713 auto window = createForeground();
8714 auto spy1 = createSpy();
8715 auto spy2 = createSpy();
8716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8717
8718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8721 window->consumeMotionDown();
8722 spy1->consumeMotionDown();
8723 spy2->consumeMotionDown();
8724
8725 // Pilfer pointers from the second spy window.
8726 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8727 spy2->assertNoEvents();
8728 spy1->consumeMotionCancel();
8729 window->consumeMotionCancel();
8730
8731 // The rest of the gesture should only be sent to the second spy window.
8732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8733 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8734 ADISPLAY_ID_DEFAULT))
8735 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8736 spy2->consumeMotionMove();
8737 spy1->assertNoEvents();
8738 window->assertNoEvents();
8739}
8740
8741/**
8742 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8743 * in the middle of the gesture.
8744 */
8745TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8746 auto window = createForeground();
8747 auto spy = createSpy();
8748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8749
8750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8751 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8752 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8753 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8754 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8755
8756 window->releaseChannel();
8757
8758 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8759
8760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8761 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8762 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8763 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8764}
8765
8766/**
8767 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8768 * the spy, but not to any other windows.
8769 */
8770TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8771 auto spy = createSpy();
8772 auto window = createForeground();
8773
8774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8775
8776 // First finger down on the window and the spy.
8777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8778 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8779 {100, 200}))
8780 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8781 spy->consumeMotionDown();
8782 window->consumeMotionDown();
8783
8784 // Spy window pilfers the pointers.
8785 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8786 window->consumeMotionCancel();
8787
8788 // Second finger down on the window and spy, but the window should not receive the pointer down.
8789 const MotionEvent secondFingerDownEvent =
8790 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8791 .displayId(ADISPLAY_ID_DEFAULT)
8792 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008793 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8794 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008795 .build();
8796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8797 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8798 InputEventInjectionSync::WAIT_FOR_RESULT))
8799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8800
Harry Cutts33476232023-01-30 19:57:29 +00008801 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008802
8803 // Third finger goes down outside all windows, so injection should fail.
8804 const MotionEvent thirdFingerDownEvent =
8805 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8806 .displayId(ADISPLAY_ID_DEFAULT)
8807 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008808 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8809 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8810 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008811 .build();
8812 ASSERT_EQ(InputEventInjectionResult::FAILED,
8813 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8814 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008815 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008816
8817 spy->assertNoEvents();
8818 window->assertNoEvents();
8819}
8820
8821/**
8822 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8823 */
8824TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8825 auto spy = createSpy();
8826 spy->setFrame(Rect(0, 0, 100, 100));
8827 auto window = createForeground();
8828 window->setFrame(Rect(0, 0, 200, 200));
8829
8830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8831
8832 // First finger down on the window only
8833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8834 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8835 {150, 150}))
8836 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8837 window->consumeMotionDown();
8838
8839 // Second finger down on the spy and window
8840 const MotionEvent secondFingerDownEvent =
8841 MotionEventBuilder(POINTER_1_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(150).y(150))
8845 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008846 .build();
8847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8848 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8849 InputEventInjectionSync::WAIT_FOR_RESULT))
8850 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8851 spy->consumeMotionDown();
8852 window->consumeMotionPointerDown(1);
8853
8854 // Third finger down on the spy and window
8855 const MotionEvent thirdFingerDownEvent =
8856 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8857 .displayId(ADISPLAY_ID_DEFAULT)
8858 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008859 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8860 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8861 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008862 .build();
8863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8864 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8865 InputEventInjectionSync::WAIT_FOR_RESULT))
8866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8867 spy->consumeMotionPointerDown(1);
8868 window->consumeMotionPointerDown(2);
8869
8870 // Spy window pilfers the pointers.
8871 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8872 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8873 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8874
8875 spy->assertNoEvents();
8876 window->assertNoEvents();
8877}
8878
8879/**
8880 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
8881 * other windows should be canceled. If this results in the cancellation of all pointers for some
8882 * window, then that window should receive ACTION_CANCEL.
8883 */
8884TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
8885 auto spy = createSpy();
8886 spy->setFrame(Rect(0, 0, 100, 100));
8887 auto window = createForeground();
8888 window->setFrame(Rect(0, 0, 200, 200));
8889
8890 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8891
8892 // First finger down on both spy and window
8893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8895 {10, 10}))
8896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8897 window->consumeMotionDown();
8898 spy->consumeMotionDown();
8899
8900 // Second finger down on the spy and window
8901 const MotionEvent secondFingerDownEvent =
8902 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8903 .displayId(ADISPLAY_ID_DEFAULT)
8904 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008905 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8906 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008907 .build();
8908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8909 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8910 InputEventInjectionSync::WAIT_FOR_RESULT))
8911 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8912 spy->consumeMotionPointerDown(1);
8913 window->consumeMotionPointerDown(1);
8914
8915 // Spy window pilfers the pointers.
8916 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8917 window->consumeMotionCancel();
8918
8919 spy->assertNoEvents();
8920 window->assertNoEvents();
8921}
8922
8923/**
8924 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
8925 * be sent to other windows
8926 */
8927TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
8928 auto spy = createSpy();
8929 spy->setFrame(Rect(0, 0, 100, 100));
8930 auto window = createForeground();
8931 window->setFrame(Rect(0, 0, 200, 200));
8932
8933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8934
8935 // First finger down on both window and spy
8936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8937 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8938 {10, 10}))
8939 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8940 window->consumeMotionDown();
8941 spy->consumeMotionDown();
8942
8943 // Spy window pilfers the pointers.
8944 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8945 window->consumeMotionCancel();
8946
8947 // Second finger down on the window only
8948 const MotionEvent secondFingerDownEvent =
8949 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8950 .displayId(ADISPLAY_ID_DEFAULT)
8951 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008952 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8953 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008954 .build();
8955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8956 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8957 InputEventInjectionSync::WAIT_FOR_RESULT))
8958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8959 window->consumeMotionDown();
8960 window->assertNoEvents();
8961
8962 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
8963 spy->consumeMotionMove();
8964 spy->assertNoEvents();
8965}
8966
Prabir Pradhand65552b2021-10-07 11:23:50 -07008967class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
8968public:
8969 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
8970 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8971 std::make_shared<FakeApplicationHandle>();
8972 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008973 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
8974 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008975 overlay->setFocusable(false);
8976 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008977 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008978 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008979 overlay->setTrustedOverlay(true);
8980
8981 std::shared_ptr<FakeApplicationHandle> application =
8982 std::make_shared<FakeApplicationHandle>();
8983 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008984 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
8985 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008986 window->setFocusable(true);
8987 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008988
8989 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8990 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8991 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008992 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008993 return {std::move(overlay), std::move(window)};
8994 }
8995
8996 void sendFingerEvent(int32_t action) {
8997 NotifyMotionArgs motionArgs =
8998 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8999 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9000 mDispatcher->notifyMotion(&motionArgs);
9001 }
9002
9003 void sendStylusEvent(int32_t action) {
9004 NotifyMotionArgs motionArgs =
9005 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9006 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9007 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9008 mDispatcher->notifyMotion(&motionArgs);
9009 }
9010};
9011
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009012using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9013
9014TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9015 ScopedSilentDeath _silentDeath;
9016
Prabir Pradhand65552b2021-10-07 11:23:50 -07009017 auto [overlay, window] = setupStylusOverlayScenario();
9018 overlay->setTrustedOverlay(false);
9019 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9020 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9021 ".* not a trusted overlay");
9022}
9023
9024TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9025 auto [overlay, window] = setupStylusOverlayScenario();
9026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9027
9028 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9029 overlay->consumeMotionDown();
9030 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9031 overlay->consumeMotionUp();
9032
9033 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9034 window->consumeMotionDown();
9035 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9036 window->consumeMotionUp();
9037
9038 overlay->assertNoEvents();
9039 window->assertNoEvents();
9040}
9041
9042TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9043 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009044 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9046
9047 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9048 overlay->consumeMotionDown();
9049 window->consumeMotionDown();
9050 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9051 overlay->consumeMotionUp();
9052 window->consumeMotionUp();
9053
9054 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9055 window->consumeMotionDown();
9056 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9057 window->consumeMotionUp();
9058
9059 overlay->assertNoEvents();
9060 window->assertNoEvents();
9061}
9062
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009063/**
9064 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9065 * The scenario is as follows:
9066 * - The stylus interceptor overlay is configured as a spy window.
9067 * - The stylus interceptor spy receives the start of a new stylus gesture.
9068 * - It pilfers pointers and then configures itself to no longer be a spy.
9069 * - The stylus interceptor continues to receive the rest of the gesture.
9070 */
9071TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9072 auto [overlay, window] = setupStylusOverlayScenario();
9073 overlay->setSpy(true);
9074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9075
9076 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9077 overlay->consumeMotionDown();
9078 window->consumeMotionDown();
9079
9080 // The interceptor pilfers the pointers.
9081 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9082 window->consumeMotionCancel();
9083
9084 // The interceptor configures itself so that it is no longer a spy.
9085 overlay->setSpy(false);
9086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9087
9088 // It continues to receive the rest of the stylus gesture.
9089 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9090 overlay->consumeMotionMove();
9091 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9092 overlay->consumeMotionUp();
9093
9094 window->assertNoEvents();
9095}
9096
Prabir Pradhan5735a322022-04-11 17:23:34 +00009097struct User {
9098 int32_t mPid;
9099 int32_t mUid;
9100 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9101 std::unique_ptr<InputDispatcher>& mDispatcher;
9102
9103 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9104 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9105
9106 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9107 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9108 ADISPLAY_ID_DEFAULT, {100, 200},
9109 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9110 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9111 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9112 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9113 }
9114
9115 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009116 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009117 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009118 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009119 mPolicyFlags);
9120 }
9121
9122 sp<FakeWindowHandle> createWindow() const {
9123 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9124 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009125 sp<FakeWindowHandle> window =
9126 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9127 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009128 window->setOwnerInfo(mPid, mUid);
9129 return window;
9130 }
9131};
9132
9133using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9134
9135TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9136 auto owner = User(mDispatcher, 10, 11);
9137 auto window = owner.createWindow();
9138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9139
9140 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9141 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9142 window->consumeMotionDown();
9143
9144 setFocusedWindow(window);
9145 window->consumeFocusEvent(true);
9146
9147 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9148 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9149 window->consumeKeyDown(ADISPLAY_ID_NONE);
9150}
9151
9152TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9153 auto owner = User(mDispatcher, 10, 11);
9154 auto window = owner.createWindow();
9155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9156
9157 auto rando = User(mDispatcher, 20, 21);
9158 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9159 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9160
9161 setFocusedWindow(window);
9162 window->consumeFocusEvent(true);
9163
9164 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9165 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9166 window->assertNoEvents();
9167}
9168
9169TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9170 auto owner = User(mDispatcher, 10, 11);
9171 auto window = owner.createWindow();
9172 auto spy = owner.createWindow();
9173 spy->setSpy(true);
9174 spy->setTrustedOverlay(true);
9175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9176
9177 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9178 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9179 spy->consumeMotionDown();
9180 window->consumeMotionDown();
9181}
9182
9183TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9184 auto owner = User(mDispatcher, 10, 11);
9185 auto window = owner.createWindow();
9186
9187 auto rando = User(mDispatcher, 20, 21);
9188 auto randosSpy = rando.createWindow();
9189 randosSpy->setSpy(true);
9190 randosSpy->setTrustedOverlay(true);
9191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9192
9193 // The event is targeted at owner's window, so injection should succeed, but the spy should
9194 // not receive the event.
9195 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9196 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9197 randosSpy->assertNoEvents();
9198 window->consumeMotionDown();
9199}
9200
9201TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9202 auto owner = User(mDispatcher, 10, 11);
9203 auto window = owner.createWindow();
9204
9205 auto rando = User(mDispatcher, 20, 21);
9206 auto randosSpy = rando.createWindow();
9207 randosSpy->setSpy(true);
9208 randosSpy->setTrustedOverlay(true);
9209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9210
9211 // A user that has injection permission can inject into any window.
9212 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9213 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9214 ADISPLAY_ID_DEFAULT));
9215 randosSpy->consumeMotionDown();
9216 window->consumeMotionDown();
9217
9218 setFocusedWindow(randosSpy);
9219 randosSpy->consumeFocusEvent(true);
9220
9221 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9222 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9223 window->assertNoEvents();
9224}
9225
9226TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9227 auto owner = User(mDispatcher, 10, 11);
9228 auto window = owner.createWindow();
9229
9230 auto rando = User(mDispatcher, 20, 21);
9231 auto randosWindow = rando.createWindow();
9232 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9233 randosWindow->setWatchOutsideTouch(true);
9234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9235
9236 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9237 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9238 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9239 window->consumeMotionDown();
9240 randosWindow->consumeMotionOutside();
9241}
9242
Garfield Tane84e6f92019-08-29 17:28:41 -07009243} // namespace android::inputdispatcher