blob: 3586a5e3b15acf29d94d0374991d50861fee4da6 [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
Siarhei Vishniakou56e79092023-02-21 19:13:16 -0800108using ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID;
109
chaviwd1c23182019-12-20 18:44:56 -0800110struct PointF {
111 float x;
112 float y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800113 auto operator<=>(const PointF&) const = default;
chaviwd1c23182019-12-20 18:44:56 -0800114};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
Gang Wang342c9272020-01-13 13:15:04 -0500116/**
117 * Return a DOWN key event with KEYCODE_A.
118 */
119static KeyEvent getTestKeyEvent() {
120 KeyEvent event;
121
Garfield Tanfbe732e2020-01-24 11:26:14 -0800122 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
123 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
124 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -0500125 return event;
126}
127
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000128static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
129 ASSERT_EQ(expectedAction, receivedAction)
130 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
131 << MotionEvent::actionToString(receivedAction);
132}
133
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800134MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
135 bool matches = action == arg.getAction();
136 if (!matches) {
137 *result_listener << "expected action " << MotionEvent::actionToString(action)
138 << ", but got " << MotionEvent::actionToString(arg.getAction());
139 }
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800140 if (action == AMOTION_EVENT_ACTION_DOWN) {
141 if (!matches) {
142 *result_listener << "; ";
143 }
144 *result_listener << "downTime should match eventTime for ACTION_DOWN events";
145 matches &= arg.getDownTime() == arg.getEventTime();
146 }
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800147 if (action == AMOTION_EVENT_ACTION_CANCEL) {
148 if (!matches) {
149 *result_listener << "; ";
150 }
151 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
152 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
153 }
154 return matches;
155}
156
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800157MATCHER_P(WithDownTime, downTime, "InputEvent with specified downTime") {
158 return arg.getDownTime() == downTime;
159}
160
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800161MATCHER_P(WithDisplayId, displayId, "InputEvent with specified displayId") {
162 return arg.getDisplayId() == displayId;
163}
164
Siarhei Vishniakouf372b812023-02-14 18:06:51 -0800165MATCHER_P(WithDeviceId, deviceId, "InputEvent with specified deviceId") {
166 return arg.getDeviceId() == deviceId;
167}
168
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800169MATCHER_P(WithSource, source, "InputEvent with specified source") {
170 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
171 << inputEventSourceToString(arg.getSource());
172 return arg.getSource() == source;
173}
174
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800175MATCHER_P(WithFlags, flags, "InputEvent with specified flags") {
176 return arg.getFlags() == flags;
177}
178
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800179MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
180 if (arg.getPointerCount() != 1) {
181 *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
182 return false;
183 }
Harry Cutts33476232023-01-30 19:57:29 +0000184 return arg.getX(/*pointerIndex=*/0) == x && arg.getY(/*pointerIndex=*/0) == y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800185}
186
Siarhei Vishniakouf372b812023-02-14 18:06:51 -0800187MATCHER_P(WithPointerCount, pointerCount, "MotionEvent with specified number of pointers") {
188 return arg.getPointerCount() == pointerCount;
189}
190
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800191MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
192 // Build a map for the received pointers, by pointer id
193 std::map<int32_t /*pointerId*/, PointF> actualPointers;
194 for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
195 const int32_t pointerId = arg.getPointerId(pointerIndex);
196 actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
197 }
198 return pointers == actualPointers;
199}
200
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201// --- FakeInputDispatcherPolicy ---
202
203class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
204 InputDispatcherConfiguration mConfig;
205
Prabir Pradhanedd96402022-02-15 01:46:16 -0800206 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
207
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000209 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210
211public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000212 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800213
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800214 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700215 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
216 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
217 EXPECT_EQ(event.getDisplayId(), args.displayId);
218
219 const auto& keyEvent = static_cast<const KeyEvent&>(event);
220 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
221 EXPECT_EQ(keyEvent.getAction(), args.action);
222 });
Jackal Guof9696682018-10-05 12:23:23 +0800223 }
224
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700225 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
226 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
227 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
228 EXPECT_EQ(event.getDisplayId(), args.displayId);
229
230 const auto& motionEvent = static_cast<const MotionEvent&>(event);
231 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
232 EXPECT_EQ(motionEvent.getAction(), args.action);
Prabir Pradhan00e029d2023-03-09 20:11:09 +0000233 EXPECT_NEAR(motionEvent.getX(0), point.x, MotionEvent::ROUNDING_PRECISION);
234 EXPECT_NEAR(motionEvent.getY(0), point.y, MotionEvent::ROUNDING_PRECISION);
235 EXPECT_NEAR(motionEvent.getRawX(0), point.x, MotionEvent::ROUNDING_PRECISION);
236 EXPECT_NEAR(motionEvent.getRawY(0), point.y, MotionEvent::ROUNDING_PRECISION);
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700237 });
Jackal Guof9696682018-10-05 12:23:23 +0800238 }
239
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700240 void assertFilterInputEventWasNotCalled() {
241 std::scoped_lock lock(mLock);
242 ASSERT_EQ(nullptr, mFilteredEvent);
243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800245 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700246 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800247 ASSERT_TRUE(mConfigurationChangedTime)
248 << "Timed out waiting for configuration changed call";
249 ASSERT_EQ(*mConfigurationChangedTime, when);
250 mConfigurationChangedTime = std::nullopt;
251 }
252
253 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700254 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800255 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800256 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800257 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
258 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
259 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
260 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
261 mLastNotifySwitch = std::nullopt;
262 }
263
chaviwfd6d3512019-03-25 13:23:49 -0700264 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700265 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800266 ASSERT_EQ(touchedToken, mOnPointerDownToken);
267 mOnPointerDownToken.clear();
268 }
269
270 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700271 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800272 ASSERT_TRUE(mOnPointerDownToken == nullptr)
273 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700274 }
275
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700276 // This function must be called soon after the expected ANR timer starts,
277 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500278 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700279 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500280 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800281 std::unique_lock lock(mLock);
282 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500283 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800284 ASSERT_NO_FATAL_FAILURE(
285 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500286 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700287 }
288
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000289 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800290 const sp<WindowInfoHandle>& window) {
291 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
292 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
293 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500294 }
295
Prabir Pradhanedd96402022-02-15 01:46:16 -0800296 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
297 const sp<IBinder>& expectedToken,
298 int32_t expectedPid) {
299 std::unique_lock lock(mLock);
300 android::base::ScopedLockAssertion assumeLocked(mLock);
301 AnrResult result;
302 ASSERT_NO_FATAL_FAILURE(result =
303 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
304 const auto& [token, pid] = result;
305 ASSERT_EQ(expectedToken, token);
306 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500307 }
308
Prabir Pradhanedd96402022-02-15 01:46:16 -0800309 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000310 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500311 std::unique_lock lock(mLock);
312 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800313 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
314 const auto& [token, _] = result;
315 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000316 }
317
Prabir Pradhanedd96402022-02-15 01:46:16 -0800318 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
319 int32_t expectedPid) {
320 std::unique_lock lock(mLock);
321 android::base::ScopedLockAssertion assumeLocked(mLock);
322 AnrResult result;
323 ASSERT_NO_FATAL_FAILURE(
324 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
325 const auto& [token, pid] = result;
326 ASSERT_EQ(expectedToken, token);
327 ASSERT_EQ(expectedPid, pid);
328 }
329
330 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000331 sp<IBinder> getResponsiveWindowToken() {
332 std::unique_lock lock(mLock);
333 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800334 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
335 const auto& [token, _] = result;
336 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700337 }
338
339 void assertNotifyAnrWasNotCalled() {
340 std::scoped_lock lock(mLock);
341 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800342 ASSERT_TRUE(mAnrWindows.empty());
343 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500344 << "ANR was not called, but please also consume the 'connection is responsive' "
345 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700346 }
347
Garfield Tan1c7bc862020-01-28 13:24:04 -0800348 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
349 mConfig.keyRepeatTimeout = timeout;
350 mConfig.keyRepeatDelay = delay;
351 }
352
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000353 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800354 std::unique_lock lock(mLock);
355 base::ScopedLockAssertion assumeLocked(mLock);
356
357 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
358 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000359 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800360 enabled;
361 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000362 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
363 << ") to be called.";
364 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800365 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000366 auto request = *mPointerCaptureRequest;
367 mPointerCaptureRequest.reset();
368 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800369 }
370
371 void assertSetPointerCaptureNotCalled() {
372 std::unique_lock lock(mLock);
373 base::ScopedLockAssertion assumeLocked(mLock);
374
375 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000376 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800377 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000378 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800379 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000380 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800381 }
382
arthurhungf452d0b2021-01-06 00:19:52 +0800383 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
384 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800385 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800386 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800387 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800388 }
389
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800390 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
391 std::unique_lock lock(mLock);
392 base::ScopedLockAssertion assumeLocked(mLock);
393 std::optional<sp<IBinder>> receivedToken =
394 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
395 mNotifyInputChannelBroken);
396 ASSERT_TRUE(receivedToken.has_value());
397 ASSERT_EQ(token, *receivedToken);
398 }
399
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800400 /**
401 * Set policy timeout. A value of zero means next key will not be intercepted.
402 */
403 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
404 mInterceptKeyTimeout = timeout;
405 }
406
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700408 std::mutex mLock;
409 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
410 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
411 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
412 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800413
Prabir Pradhan99987712020-11-10 18:43:05 -0800414 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000415
416 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800417
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700418 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700419 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800420 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
421 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700422 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800423 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
424 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700425
arthurhungf452d0b2021-01-06 00:19:52 +0800426 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800427 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800428
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800429 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
430
Prabir Pradhanedd96402022-02-15 01:46:16 -0800431 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
432 // for a specific container to become non-empty. When the container is non-empty, return the
433 // first entry from the container and erase it.
434 template <class T>
435 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
436 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
437 // If there is an ANR, Dispatcher won't be idle because there are still events
438 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
439 // before checking if ANR was called.
440 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
441 // to provide it some time to act. 100ms seems reasonable.
442 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
443 const std::chrono::time_point start = std::chrono::steady_clock::now();
444 std::optional<T> token =
445 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
446 if (!token.has_value()) {
447 ADD_FAILURE() << "Did not receive the ANR callback";
448 return {};
449 }
450
451 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
452 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
453 // the dispatcher started counting before this function was called
454 if (std::chrono::abs(timeout - waited) > 100ms) {
455 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
456 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
457 << "ms, but waited "
458 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
459 << "ms instead";
460 }
461 return *token;
462 }
463
464 template <class T>
465 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
466 std::queue<T>& storage,
467 std::unique_lock<std::mutex>& lock,
468 std::condition_variable& condition)
469 REQUIRES(mLock) {
470 condition.wait_for(lock, timeout,
471 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
472 if (storage.empty()) {
473 ADD_FAILURE() << "Did not receive the expected callback";
474 return std::nullopt;
475 }
476 T item = storage.front();
477 storage.pop();
478 return std::make_optional(item);
479 }
480
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600481 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700482 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800483 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484 }
485
Prabir Pradhanedd96402022-02-15 01:46:16 -0800486 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
487 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700488 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800489 ASSERT_TRUE(pid.has_value());
490 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700491 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500492 }
493
Prabir Pradhanedd96402022-02-15 01:46:16 -0800494 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
495 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500496 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800497 ASSERT_TRUE(pid.has_value());
498 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500499 mNotifyAnr.notify_all();
500 }
501
502 void notifyNoFocusedWindowAnr(
503 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
504 std::scoped_lock lock(mLock);
505 mAnrApplications.push(applicationHandle);
506 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 }
508
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800509 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
510 std::scoped_lock lock(mLock);
511 mBrokenInputChannels.push(connectionToken);
512 mNotifyInputChannelBroken.notify_all();
513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600515 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700516
Chris Yef59a2f42020-10-16 12:55:26 -0700517 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
518 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
519 const std::vector<float>& values) override {}
520
521 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
522 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000523
Chris Yefb552902021-02-03 17:18:37 -0800524 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
525
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600526 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 *outConfig = mConfig;
528 }
529
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600530 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700531 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800532 switch (inputEvent->getType()) {
533 case AINPUT_EVENT_TYPE_KEY: {
534 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800535 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800536 break;
537 }
538
539 case AINPUT_EVENT_TYPE_MOTION: {
540 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800541 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800542 break;
543 }
544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 return true;
546 }
547
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800548 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
549 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
550 // Clear intercept state when we handled the event.
551 mInterceptKeyTimeout = 0ms;
552 }
553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600555 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600557 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800558 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
559 // Clear intercept state so we could dispatch the event in next wake.
560 mInterceptKeyTimeout = 0ms;
561 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600564 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 return false;
566 }
567
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600568 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
569 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700570 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800571 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
572 * essentially a passthrough for notifySwitch.
573 */
Harry Cutts33476232023-01-30 19:57:29 +0000574 mLastNotifySwitch = NotifySwitchArgs(/*id=*/1, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 }
576
Sean Stoutb4e0a592021-02-23 07:34:53 -0800577 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600579 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700580 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700581 mOnPointerDownToken = newToken;
582 }
583
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000584 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800585 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000586 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800587 mPointerCaptureChangedCondition.notify_all();
588 }
589
arthurhungf452d0b2021-01-06 00:19:52 +0800590 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
591 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800592 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800593 mDropTargetWindowToken = token;
594 }
595
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700596 void assertFilterInputEventWasCalledInternal(
597 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700598 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800599 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700600 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800601 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603};
604
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605// --- InputDispatcherTest ---
606
607class InputDispatcherTest : public testing::Test {
608protected:
609 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700610 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000612 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700613 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800614 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800615 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000616 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700617 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 }
619
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000620 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700621 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700623 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700625
626 /**
627 * Used for debugging when writing the test
628 */
629 void dumpDispatcherState() {
630 std::string dump;
631 mDispatcher->dump(dump);
632 std::stringstream ss(dump);
633 std::string to;
634
635 while (std::getline(ss, to, '\n')) {
636 ALOGE("%s", to.c_str());
637 }
638 }
Vishnu Nair958da932020-08-21 17:12:37 -0700639
chaviw3277faf2021-05-19 16:45:23 -0500640 void setFocusedWindow(const sp<WindowInfoHandle>& window,
641 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700642 FocusRequest request;
643 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000644 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700645 if (focusedWindow) {
646 request.focusedToken = focusedWindow->getToken();
647 }
648 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
649 request.displayId = window->getInfo()->displayId;
650 mDispatcher->setFocusedWindow(request);
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652};
653
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
655 KeyEvent event;
656
657 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800658 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
659 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600660 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
661 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800662 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000663 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000664 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 << "Should reject key events with undefined action.";
666
667 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800668 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
669 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600670 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000672 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000673 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 << "Should reject key events with ACTION_MULTIPLE.";
675}
676
677TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
678 MotionEvent event;
679 PointerProperties pointerProperties[MAX_POINTERS + 1];
680 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800681 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 pointerProperties[i].clear();
683 pointerProperties[i].id = i;
684 pointerCoords[i].clear();
685 }
686
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800687 // Some constants commonly used below
688 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
689 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
690 constexpr int32_t metaState = AMETA_NONE;
691 constexpr MotionClassification classification = MotionClassification::NONE;
692
chaviw9eaa22c2020-07-01 16:21:27 -0700693 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800695 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700696 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
697 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700698 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
699 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700700 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800701 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000702 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000703 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 << "Should reject motion events with undefined action.";
705
706 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800707 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800708 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
709 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
710 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
711 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500712 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800713 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000714 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000715 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 << "Should reject motion events with pointer down index too large.";
717
Garfield Tanfbe732e2020-01-24 11:26:14 -0800718 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700719 AMOTION_EVENT_ACTION_POINTER_DOWN |
720 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700721 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
722 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700723 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500724 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800725 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000726 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000727 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 << "Should reject motion events with pointer down index too small.";
729
730 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800731 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800732 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
733 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
734 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
735 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500736 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000738 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000739 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 << "Should reject motion events with pointer up index too large.";
741
Garfield Tanfbe732e2020-01-24 11:26:14 -0800742 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700743 AMOTION_EVENT_ACTION_POINTER_UP |
744 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700745 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
746 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700747 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500748 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800749 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000750 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000751 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 << "Should reject motion events with pointer up index too small.";
753
754 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800755 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
756 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700757 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700758 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
759 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700760 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800761 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000762 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000763 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 << "Should reject motion events with 0 pointers.";
765
Garfield Tanfbe732e2020-01-24 11:26:14 -0800766 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
767 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700768 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700769 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
770 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800772 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000773 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000774 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 << "Should reject motion events with more than MAX_POINTERS pointers.";
776
777 // Rejects motion events with invalid pointer ids.
778 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800779 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
780 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700781 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700782 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
783 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700784 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800785 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000786 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000787 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 << "Should reject motion events with pointer ids less than 0.";
789
790 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800791 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
792 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700793 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700794 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
795 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700796 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800797 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000798 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000799 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
801
802 // Rejects motion events with duplicate pointer ids.
803 pointerProperties[0].id = 1;
804 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800805 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
806 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700807 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700808 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
809 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700810 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800811 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000812 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000813 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 << "Should reject motion events with duplicate pointer ids.";
815}
816
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800817/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
818
819TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
820 constexpr nsecs_t eventTime = 20;
Harry Cutts33476232023-01-30 19:57:29 +0000821 NotifyConfigurationChangedArgs args(/*id=*/10, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800822 mDispatcher->notifyConfigurationChanged(&args);
823 ASSERT_TRUE(mDispatcher->waitForIdle());
824
825 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
826}
827
828TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Harry Cutts33476232023-01-30 19:57:29 +0000829 NotifySwitchArgs args(/*id=*/10, /*eventTime=*/20, /*policyFlags=*/0, /*switchValues=*/1,
830 /*switchMask=*/2);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800831 mDispatcher->notifySwitch(&args);
832
833 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
834 args.policyFlags |= POLICY_FLAG_TRUSTED;
835 mFakePolicy->assertNotifySwitchWasCalled(args);
836}
837
Arthur Hungb92218b2018-08-14 12:00:21 +0800838// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700839static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700840// Default input dispatching timeout if there is no focused application or paused window
841// from which to determine an appropriate dispatching timeout.
842static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
843 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
844 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800845
846class FakeApplicationHandle : public InputApplicationHandle {
847public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700848 FakeApplicationHandle() {
849 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700850 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500851 mInfo.dispatchingTimeoutMillis =
852 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700853 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800854 virtual ~FakeApplicationHandle() {}
855
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000856 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700857
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500858 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
859 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700860 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800861};
862
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800863class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800864public:
Garfield Tan15601662020-09-22 15:32:38 -0700865 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800866 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700867 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800868 }
869
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800870 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700871 InputEvent* event;
872 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
873 if (!consumeSeq) {
874 return nullptr;
875 }
876 finishEvent(*consumeSeq);
877 return event;
878 }
879
880 /**
881 * Receive an event without acknowledging it.
882 * Return the sequence number that could later be used to send finished signal.
883 */
884 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800885 uint32_t consumeSeq;
886 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800887
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800888 std::chrono::time_point start = std::chrono::steady_clock::now();
889 status_t status = WOULD_BLOCK;
890 while (status == WOULD_BLOCK) {
Harry Cutts33476232023-01-30 19:57:29 +0000891 status = mConsumer->consume(&mEventFactory, /*consumeBatches=*/true, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800892 &event);
893 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
894 if (elapsed > 100ms) {
895 break;
896 }
897 }
898
899 if (status == WOULD_BLOCK) {
900 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700901 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800902 }
903
904 if (status != OK) {
905 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700906 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800907 }
908 if (event == nullptr) {
909 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700910 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800911 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700912 if (outEvent != nullptr) {
913 *outEvent = event;
914 }
915 return consumeSeq;
916 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800917
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700918 /**
919 * To be used together with "receiveEvent" to complete the consumption of an event.
920 */
921 void finishEvent(uint32_t consumeSeq) {
922 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
923 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800924 }
925
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000926 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
927 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
928 ASSERT_EQ(OK, status);
929 }
930
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000931 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
932 std::optional<int32_t> expectedDisplayId,
933 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800934 InputEvent* event = consume();
935
936 ASSERT_NE(nullptr, event) << mName.c_str()
937 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800938 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800940 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800941
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000942 if (expectedDisplayId.has_value()) {
943 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
944 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800945
Tiger Huang8664f8c2018-10-11 19:14:35 +0800946 switch (expectedEventType) {
947 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800948 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
949 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000950 if (expectedFlags.has_value()) {
951 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
952 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800953 break;
954 }
955 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800956 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000957 assertMotionAction(expectedAction, motionEvent.getAction());
958
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000959 if (expectedFlags.has_value()) {
960 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
961 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800962 break;
963 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100964 case AINPUT_EVENT_TYPE_FOCUS: {
965 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
966 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800967 case AINPUT_EVENT_TYPE_CAPTURE: {
968 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
969 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000970 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
971 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
972 }
arthurhungb89ccb02020-12-30 16:19:01 +0800973 case AINPUT_EVENT_TYPE_DRAG: {
974 FAIL() << "Use 'consumeDragEvent' for DRAG events";
975 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800976 default: {
977 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
978 }
979 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800980 }
981
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800982 MotionEvent* consumeMotion() {
983 InputEvent* event = consume();
984
985 if (event == nullptr) {
986 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
987 return nullptr;
988 }
989
990 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
991 ADD_FAILURE() << mName << " expected a MotionEvent, got "
992 << inputEventTypeToString(event->getType()) << " event";
993 return nullptr;
994 }
995 return static_cast<MotionEvent*>(event);
996 }
997
998 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
999 MotionEvent* motionEvent = consumeMotion();
1000 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
1001 ASSERT_THAT(*motionEvent, matcher);
1002 }
1003
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001004 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
1005 InputEvent* event = consume();
1006 ASSERT_NE(nullptr, event) << mName.c_str()
1007 << ": consumer should have returned non-NULL event.";
1008 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
1009 << "Got " << inputEventTypeToString(event->getType())
1010 << " event instead of FOCUS event";
1011
1012 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1013 << mName.c_str() << ": event displayId should always be NONE.";
1014
1015 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
1016 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001017 }
1018
Prabir Pradhan99987712020-11-10 18:43:05 -08001019 void consumeCaptureEvent(bool hasCapture) {
1020 const InputEvent* event = consume();
1021 ASSERT_NE(nullptr, event) << mName.c_str()
1022 << ": consumer should have returned non-NULL event.";
1023 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
1024 << "Got " << inputEventTypeToString(event->getType())
1025 << " event instead of CAPTURE event";
1026
1027 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1028 << mName.c_str() << ": event displayId should always be NONE.";
1029
1030 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1031 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1032 }
1033
arthurhungb89ccb02020-12-30 16:19:01 +08001034 void consumeDragEvent(bool isExiting, float x, float y) {
1035 const InputEvent* event = consume();
1036 ASSERT_NE(nullptr, event) << mName.c_str()
1037 << ": consumer should have returned non-NULL event.";
1038 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1039 << "Got " << inputEventTypeToString(event->getType())
1040 << " event instead of DRAG event";
1041
1042 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1043 << mName.c_str() << ": event displayId should always be NONE.";
1044
1045 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1046 EXPECT_EQ(isExiting, dragEvent.isExiting());
1047 EXPECT_EQ(x, dragEvent.getX());
1048 EXPECT_EQ(y, dragEvent.getY());
1049 }
1050
Antonio Kantekf16f2832021-09-28 04:39:20 +00001051 void consumeTouchModeEvent(bool inTouchMode) {
1052 const InputEvent* event = consume();
1053 ASSERT_NE(nullptr, event) << mName.c_str()
1054 << ": consumer should have returned non-NULL event.";
1055 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1056 << "Got " << inputEventTypeToString(event->getType())
1057 << " event instead of TOUCH_MODE event";
1058
1059 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1060 << mName.c_str() << ": event displayId should always be NONE.";
1061 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1062 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1063 }
1064
chaviwd1c23182019-12-20 18:44:56 -08001065 void assertNoEvents() {
1066 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 if (event == nullptr) {
1068 return;
1069 }
1070 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1071 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1072 ADD_FAILURE() << "Received key event "
1073 << KeyEvent::actionToString(keyEvent.getAction());
1074 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1075 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1076 ADD_FAILURE() << "Received motion event "
1077 << MotionEvent::actionToString(motionEvent.getAction());
1078 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1079 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1080 ADD_FAILURE() << "Received focus event, hasFocus = "
1081 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001082 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1083 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1084 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1085 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001086 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1087 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1088 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1089 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001090 }
1091 FAIL() << mName.c_str()
1092 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001093 }
1094
1095 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1096
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001097 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1098
chaviwd1c23182019-12-20 18:44:56 -08001099protected:
1100 std::unique_ptr<InputConsumer> mConsumer;
1101 PreallocatedInputEventFactory mEventFactory;
1102
1103 std::string mName;
1104};
1105
chaviw3277faf2021-05-19 16:45:23 -05001106class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001107public:
1108 static const int32_t WIDTH = 600;
1109 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001110
Chris Yea209fde2020-07-22 13:54:51 -07001111 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001112 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001113 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001114 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001115 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001116 base::Result<std::unique_ptr<InputChannel>> channel =
1117 dispatcher->createInputChannel(name);
1118 token = (*channel)->getConnectionToken();
1119 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001120 }
1121
1122 inputApplicationHandle->updateInfo();
1123 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1124
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001125 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001126 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001127 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001128 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001129 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001130 mInfo.frameLeft = 0;
1131 mInfo.frameTop = 0;
1132 mInfo.frameRight = WIDTH;
1133 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001134 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001135 mInfo.globalScaleFactor = 1.0;
1136 mInfo.touchableRegion.clear();
1137 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001138 mInfo.ownerPid = WINDOW_PID;
1139 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001140 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001141 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001142 }
1143
Arthur Hungabbb9d82021-09-01 14:52:30 +00001144 sp<FakeWindowHandle> clone(
1145 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001146 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001147 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001148 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1149 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001150 return handle;
1151 }
1152
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001153 void setTouchable(bool touchable) {
1154 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1155 }
chaviwd1c23182019-12-20 18:44:56 -08001156
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001157 void setFocusable(bool focusable) {
1158 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1159 }
1160
1161 void setVisible(bool visible) {
1162 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1163 }
Vishnu Nair958da932020-08-21 17:12:37 -07001164
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001165 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001166 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001167 }
1168
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001169 void setPaused(bool paused) {
1170 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1171 }
1172
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001173 void setPreventSplitting(bool preventSplitting) {
1174 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001175 }
1176
1177 void setSlippery(bool slippery) {
1178 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1179 }
1180
1181 void setWatchOutsideTouch(bool watchOutside) {
1182 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1183 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001184
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001185 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1186
1187 void setInterceptsStylus(bool interceptsStylus) {
1188 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1189 }
1190
1191 void setDropInput(bool dropInput) {
1192 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1193 }
1194
1195 void setDropInputIfObscured(bool dropInputIfObscured) {
1196 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1197 }
1198
1199 void setNoInputChannel(bool noInputChannel) {
1200 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1201 }
1202
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001203 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1204
chaviw3277faf2021-05-19 16:45:23 -05001205 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001206
Bernardo Rufino7393d172021-02-26 13:56:11 +00001207 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1208
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001209 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001210 mInfo.frameLeft = frame.left;
1211 mInfo.frameTop = frame.top;
1212 mInfo.frameRight = frame.right;
1213 mInfo.frameBottom = frame.bottom;
1214 mInfo.touchableRegion.clear();
1215 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001216
1217 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1218 ui::Transform translate;
1219 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1220 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001221 }
1222
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001223 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1224
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001225 void setIsWallpaper(bool isWallpaper) {
1226 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1227 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001228
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001229 void setDupTouchToWallpaper(bool hasWallpaper) {
1230 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1231 }
chaviwd1c23182019-12-20 18:44:56 -08001232
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001233 void setTrustedOverlay(bool trustedOverlay) {
1234 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1235 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001236
chaviw9eaa22c2020-07-01 16:21:27 -07001237 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1238 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1239 }
1240
1241 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001242
yunho.shinf4a80b82020-11-16 21:13:57 +09001243 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1244
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001245 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1246 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1247 expectedFlags);
1248 }
1249
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001250 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1251 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1252 }
1253
Svet Ganov5d3bc372020-01-26 23:11:07 -08001254 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001255 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001256 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1257 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001258 }
1259
1260 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001261 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001262 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1263 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001264 }
1265
1266 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001267 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001268 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1269 }
1270
1271 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1272 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001273 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1274 expectedFlags);
1275 }
1276
Svet Ganov5d3bc372020-01-26 23:11:07 -08001277 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001278 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1279 int32_t expectedFlags = 0) {
1280 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1281 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001282 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1283 }
1284
1285 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001286 int32_t expectedFlags = 0) {
1287 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1288 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001289 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1290 }
1291
1292 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001293 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001294 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1295 expectedFlags);
1296 }
1297
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001298 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1299 int32_t expectedFlags = 0) {
1300 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1301 expectedFlags);
1302 }
1303
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001304 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1305 int32_t expectedFlags = 0) {
1306 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001307 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001308 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1309 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1310 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1311 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1312 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1313 }
1314
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001315 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1316 ASSERT_NE(mInputReceiver, nullptr)
1317 << "Cannot consume events from a window with no receiver";
1318 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1319 }
1320
Prabir Pradhan99987712020-11-10 18:43:05 -08001321 void consumeCaptureEvent(bool hasCapture) {
1322 ASSERT_NE(mInputReceiver, nullptr)
1323 << "Cannot consume events from a window with no receiver";
1324 mInputReceiver->consumeCaptureEvent(hasCapture);
1325 }
1326
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001327 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1328 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001329 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001330 ASSERT_THAT(*motionEvent, matcher);
1331 }
1332
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001333 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1334 std::optional<int32_t> expectedDisplayId,
1335 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001336 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1337 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1338 expectedFlags);
1339 }
1340
arthurhungb89ccb02020-12-30 16:19:01 +08001341 void consumeDragEvent(bool isExiting, float x, float y) {
1342 mInputReceiver->consumeDragEvent(isExiting, x, y);
1343 }
1344
Antonio Kantekf16f2832021-09-28 04:39:20 +00001345 void consumeTouchModeEvent(bool inTouchMode) {
1346 ASSERT_NE(mInputReceiver, nullptr)
1347 << "Cannot consume events from a window with no receiver";
1348 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1349 }
1350
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001351 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001352 if (mInputReceiver == nullptr) {
1353 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1354 return std::nullopt;
1355 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001356 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001357 }
1358
1359 void finishEvent(uint32_t sequenceNum) {
1360 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1361 mInputReceiver->finishEvent(sequenceNum);
1362 }
1363
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001364 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1365 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1366 mInputReceiver->sendTimeline(inputEventId, timeline);
1367 }
1368
chaviwaf87b3e2019-10-01 16:59:28 -07001369 InputEvent* consume() {
1370 if (mInputReceiver == nullptr) {
1371 return nullptr;
1372 }
1373 return mInputReceiver->consume();
1374 }
1375
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001376 MotionEvent* consumeMotion() {
1377 InputEvent* event = consume();
1378 if (event == nullptr) {
1379 ADD_FAILURE() << "Consume failed : no event";
1380 return nullptr;
1381 }
1382 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1383 ADD_FAILURE() << "Instead of motion event, got "
1384 << inputEventTypeToString(event->getType());
1385 return nullptr;
1386 }
1387 return static_cast<MotionEvent*>(event);
1388 }
1389
Arthur Hungb92218b2018-08-14 12:00:21 +08001390 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001391 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001392 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001393 return; // Can't receive events if the window does not have input channel
1394 }
1395 ASSERT_NE(nullptr, mInputReceiver)
1396 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001397 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001398 }
1399
chaviwaf87b3e2019-10-01 16:59:28 -07001400 sp<IBinder> getToken() { return mInfo.token; }
1401
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001402 const std::string& getName() { return mName; }
1403
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001404 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1405 mInfo.ownerPid = ownerPid;
1406 mInfo.ownerUid = ownerUid;
1407 }
1408
Prabir Pradhanedd96402022-02-15 01:46:16 -08001409 int32_t getPid() const { return mInfo.ownerPid; }
1410
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001411 void destroyReceiver() { mInputReceiver = nullptr; }
1412
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001413 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1414
chaviwd1c23182019-12-20 18:44:56 -08001415private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001416 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001417 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001418 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001419};
1420
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001421std::atomic<int32_t> FakeWindowHandle::sId{1};
1422
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001423static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001424 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001425 int32_t displayId = ADISPLAY_ID_NONE,
1426 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001427 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001428 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1429 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001430 KeyEvent event;
1431 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1432
1433 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001434 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Harry Cutts33476232023-01-30 19:57:29 +00001435 INVALID_HMAC, action, /*flags=*/0, AKEYCODE_A, KEY_A, AMETA_NONE, repeatCount,
1436 currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001437
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001438 if (!allowKeyRepeat) {
1439 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1440 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001441 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001442 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001443}
1444
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001445static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001446 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001447 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001448}
1449
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001450// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1451// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1452// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453static InputEventInjectionResult injectKeyDownNoRepeat(
1454 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001455 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001456 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
Harry Cutts33476232023-01-30 19:57:29 +00001457 /*allowKeyRepeat=*/false);
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001458}
1459
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001460static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001462 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /*repeatCount=*/0, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463}
1464
Garfield Tandf26e862020-07-01 20:18:19 -07001465class PointerBuilder {
1466public:
1467 PointerBuilder(int32_t id, int32_t toolType) {
1468 mProperties.clear();
1469 mProperties.id = id;
1470 mProperties.toolType = toolType;
1471 mCoords.clear();
1472 }
1473
1474 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1475
1476 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1477
1478 PointerBuilder& axis(int32_t axis, float value) {
1479 mCoords.setAxisValue(axis, value);
1480 return *this;
1481 }
1482
1483 PointerProperties buildProperties() const { return mProperties; }
1484
1485 PointerCoords buildCoords() const { return mCoords; }
1486
1487private:
1488 PointerProperties mProperties;
1489 PointerCoords mCoords;
1490};
1491
1492class MotionEventBuilder {
1493public:
1494 MotionEventBuilder(int32_t action, int32_t source) {
1495 mAction = action;
1496 mSource = source;
1497 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001498 mDownTime = mEventTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001499 }
1500
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001501 MotionEventBuilder& deviceId(int32_t deviceId) {
1502 mDeviceId = deviceId;
1503 return *this;
1504 }
1505
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001506 MotionEventBuilder& downTime(nsecs_t downTime) {
1507 mDownTime = downTime;
1508 return *this;
1509 }
1510
Garfield Tandf26e862020-07-01 20:18:19 -07001511 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1512 mEventTime = eventTime;
1513 return *this;
1514 }
1515
1516 MotionEventBuilder& displayId(int32_t displayId) {
1517 mDisplayId = displayId;
1518 return *this;
1519 }
1520
1521 MotionEventBuilder& actionButton(int32_t actionButton) {
1522 mActionButton = actionButton;
1523 return *this;
1524 }
1525
arthurhung6d4bed92021-03-17 11:59:33 +08001526 MotionEventBuilder& buttonState(int32_t buttonState) {
1527 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001528 return *this;
1529 }
1530
1531 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1532 mRawXCursorPosition = rawXCursorPosition;
1533 return *this;
1534 }
1535
1536 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1537 mRawYCursorPosition = rawYCursorPosition;
1538 return *this;
1539 }
1540
1541 MotionEventBuilder& pointer(PointerBuilder pointer) {
1542 mPointers.push_back(pointer);
1543 return *this;
1544 }
1545
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001546 MotionEventBuilder& addFlag(uint32_t flags) {
1547 mFlags |= flags;
1548 return *this;
1549 }
1550
Garfield Tandf26e862020-07-01 20:18:19 -07001551 MotionEvent build() {
1552 std::vector<PointerProperties> pointerProperties;
1553 std::vector<PointerCoords> pointerCoords;
1554 for (const PointerBuilder& pointer : mPointers) {
1555 pointerProperties.push_back(pointer.buildProperties());
1556 pointerCoords.push_back(pointer.buildCoords());
1557 }
1558
1559 // Set mouse cursor position for the most common cases to avoid boilerplate.
1560 if (mSource == AINPUT_SOURCE_MOUSE &&
1561 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1562 mPointers.size() == 1) {
1563 mRawXCursorPosition = pointerCoords[0].getX();
1564 mRawYCursorPosition = pointerCoords[0].getY();
1565 }
1566
1567 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001568 ui::Transform identityTransform;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001569 event.initialize(InputEvent::nextId(), mDeviceId, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001570 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001571 mButtonState, MotionClassification::NONE, identityTransform,
1572 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001573 mRawYCursorPosition, identityTransform, mDownTime, mEventTime,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001574 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001575
1576 return event;
1577 }
1578
1579private:
1580 int32_t mAction;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001581 int32_t mDeviceId = DEVICE_ID;
Garfield Tandf26e862020-07-01 20:18:19 -07001582 int32_t mSource;
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001583 nsecs_t mDownTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001584 nsecs_t mEventTime;
1585 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1586 int32_t mActionButton{0};
1587 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001588 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001589 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1590 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1591
1592 std::vector<PointerBuilder> mPointers;
1593};
1594
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08001595class MotionArgsBuilder {
1596public:
1597 MotionArgsBuilder(int32_t action, int32_t source) {
1598 mAction = action;
1599 mSource = source;
1600 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1601 mDownTime = mEventTime;
1602 }
1603
1604 MotionArgsBuilder& deviceId(int32_t deviceId) {
1605 mDeviceId = deviceId;
1606 return *this;
1607 }
1608
1609 MotionArgsBuilder& downTime(nsecs_t downTime) {
1610 mDownTime = downTime;
1611 return *this;
1612 }
1613
1614 MotionArgsBuilder& eventTime(nsecs_t eventTime) {
1615 mEventTime = eventTime;
1616 return *this;
1617 }
1618
1619 MotionArgsBuilder& displayId(int32_t displayId) {
1620 mDisplayId = displayId;
1621 return *this;
1622 }
1623
1624 MotionArgsBuilder& policyFlags(int32_t policyFlags) {
1625 mPolicyFlags = policyFlags;
1626 return *this;
1627 }
1628
1629 MotionArgsBuilder& actionButton(int32_t actionButton) {
1630 mActionButton = actionButton;
1631 return *this;
1632 }
1633
1634 MotionArgsBuilder& buttonState(int32_t buttonState) {
1635 mButtonState = buttonState;
1636 return *this;
1637 }
1638
1639 MotionArgsBuilder& rawXCursorPosition(float rawXCursorPosition) {
1640 mRawXCursorPosition = rawXCursorPosition;
1641 return *this;
1642 }
1643
1644 MotionArgsBuilder& rawYCursorPosition(float rawYCursorPosition) {
1645 mRawYCursorPosition = rawYCursorPosition;
1646 return *this;
1647 }
1648
1649 MotionArgsBuilder& pointer(PointerBuilder pointer) {
1650 mPointers.push_back(pointer);
1651 return *this;
1652 }
1653
1654 MotionArgsBuilder& addFlag(uint32_t flags) {
1655 mFlags |= flags;
1656 return *this;
1657 }
1658
1659 NotifyMotionArgs build() {
1660 std::vector<PointerProperties> pointerProperties;
1661 std::vector<PointerCoords> pointerCoords;
1662 for (const PointerBuilder& pointer : mPointers) {
1663 pointerProperties.push_back(pointer.buildProperties());
1664 pointerCoords.push_back(pointer.buildCoords());
1665 }
1666
1667 // Set mouse cursor position for the most common cases to avoid boilerplate.
1668 if (mSource == AINPUT_SOURCE_MOUSE &&
1669 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1670 mPointers.size() == 1) {
1671 mRawXCursorPosition = pointerCoords[0].getX();
1672 mRawYCursorPosition = pointerCoords[0].getY();
1673 }
1674
1675 NotifyMotionArgs args(InputEvent::nextId(), mEventTime, /*readTime=*/mEventTime, mDeviceId,
1676 mSource, mDisplayId, mPolicyFlags, mAction, mActionButton, mFlags,
1677 AMETA_NONE, mButtonState, MotionClassification::NONE, /*edgeFlags=*/0,
1678 mPointers.size(), pointerProperties.data(), pointerCoords.data(),
1679 /*xPrecision=*/0, /*yPrecision=*/0, mRawXCursorPosition,
1680 mRawYCursorPosition, mDownTime, /*videoFrames=*/{});
1681
1682 return args;
1683 }
1684
1685private:
1686 int32_t mAction;
1687 int32_t mDeviceId = DEVICE_ID;
1688 int32_t mSource;
1689 nsecs_t mDownTime;
1690 nsecs_t mEventTime;
1691 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1692 int32_t mPolicyFlags = DEFAULT_POLICY_FLAGS;
1693 int32_t mActionButton{0};
1694 int32_t mButtonState{0};
1695 int32_t mFlags{0};
1696 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1697 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1698
1699 std::vector<PointerBuilder> mPointers;
1700};
1701
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001702static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001703 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001704 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001705 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1706 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1707 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1708 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001709}
1710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001711static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001712 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001713 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001714 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001715 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1716 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001718 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1719 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001720 MotionEvent event = MotionEventBuilder(action, source)
1721 .displayId(displayId)
1722 .eventTime(eventTime)
1723 .rawXCursorPosition(cursorPosition.x)
1724 .rawYCursorPosition(cursorPosition.y)
Harry Cutts33476232023-01-30 19:57:29 +00001725 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001726 .x(position.x)
1727 .y(position.y))
1728 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001729
1730 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001731 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1732 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001733}
1734
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001735static InputEventInjectionResult injectMotionDown(
1736 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1737 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001738 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001739}
1740
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001741static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001742 int32_t source, int32_t displayId,
1743 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001744 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001745}
1746
Jackal Guof9696682018-10-05 12:23:23 +08001747static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1748 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1749 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001750 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001751 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1752 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001753
1754 return args;
1755}
1756
chaviwd1c23182019-12-20 18:44:56 -08001757static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1758 const std::vector<PointF>& points) {
1759 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001760 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1761 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1762 }
1763
chaviwd1c23182019-12-20 18:44:56 -08001764 PointerProperties pointerProperties[pointerCount];
1765 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001766
chaviwd1c23182019-12-20 18:44:56 -08001767 for (size_t i = 0; i < pointerCount; i++) {
1768 pointerProperties[i].clear();
1769 pointerProperties[i].id = i;
1770 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001771
chaviwd1c23182019-12-20 18:44:56 -08001772 pointerCoords[i].clear();
1773 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1774 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1775 }
Jackal Guof9696682018-10-05 12:23:23 +08001776
1777 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1778 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001779 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001780 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1781 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001782 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1783 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001784 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1785 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001786
1787 return args;
1788}
1789
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001790static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1791 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1792}
1793
chaviwd1c23182019-12-20 18:44:56 -08001794static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1795 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1796}
1797
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001798static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1799 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001800 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001801}
1802
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001803/**
1804 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1805 * broken channel.
1806 */
1807TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1808 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1809 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001810 sp<FakeWindowHandle>::make(application, mDispatcher,
1811 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001812
1813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1814
1815 // Window closes its channel, but the window remains.
1816 window->destroyReceiver();
1817 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1818}
1819
Arthur Hungb92218b2018-08-14 12:00:21 +08001820TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001821 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001822 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1823 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001824
Arthur Hung72d8dc32020-03-28 00:48:39 +00001825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1827 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1828 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001829
1830 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001831 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001832}
1833
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001834TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1835 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001836 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1837 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001838
1839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1840 // Inject a MotionEvent to an unknown display.
1841 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1842 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1843 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1844
1845 // Window should receive motion event.
1846 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1847}
1848
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001849/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001850 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001851 * This test serves as a sanity check for the next test, where setInputWindows is
1852 * called twice.
1853 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001854TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001856 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1857 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001858 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001859
1860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1863 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001864 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001865
1866 // Window should receive motion event.
1867 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1868}
1869
1870/**
1871 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001872 */
1873TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001875 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1876 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001877 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001878
1879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001882 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1883 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001885
1886 // Window should receive motion event.
1887 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1888}
1889
Arthur Hungb92218b2018-08-14 12:00:21 +08001890// The foreground window should receive the first touch down event.
1891TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001892 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001893 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001894 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001895 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001896 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001897
Arthur Hung72d8dc32020-03-28 00:48:39 +00001898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1900 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1901 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001902
1903 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001904 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001905 windowSecond->assertNoEvents();
1906}
1907
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001908/**
1909 * Two windows: A top window, and a wallpaper behind the window.
1910 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1911 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001912 * 1. foregroundWindow <-- dup touch to wallpaper
1913 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001914 */
1915TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1917 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001918 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001919 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001920 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001921 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001922 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001923
1924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1926 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1927 {100, 200}))
1928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1929
1930 // Both foreground window and its wallpaper should receive the touch down
1931 foregroundWindow->consumeMotionDown();
1932 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1933
1934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1935 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1936 ADISPLAY_ID_DEFAULT, {110, 200}))
1937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1938
1939 foregroundWindow->consumeMotionMove();
1940 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1941
1942 // Now the foreground window goes away, but the wallpaper stays
1943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1944 foregroundWindow->consumeMotionCancel();
1945 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1946 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1947}
1948
1949/**
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001950 * Two fingers down on the window, and lift off the first finger.
1951 * Next, cancel the gesture to the window by removing the window. Make sure that the CANCEL event
1952 * contains a single pointer.
1953 */
1954TEST_F(InputDispatcherTest, CancelAfterPointer0Up) {
1955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1956 sp<FakeWindowHandle> window =
1957 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1958
1959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1960 NotifyMotionArgs args;
1961 // First touch pointer down on right window
1962 mDispatcher->notifyMotion(&(
1963 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1964 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1965 .build()));
1966 // Second touch pointer down
1967 mDispatcher->notifyMotion(&(
1968 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1969
1970 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1971 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(110).y(100))
1972 .build()));
1973 // First touch pointer lifts. The second one remains down
1974 mDispatcher->notifyMotion(&(
1975 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1976
1977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1978 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(110).y(100))
1979 .build()));
1980 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
1981 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
1982 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
1983
1984 // Remove the window. The gesture should be canceled
1985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
1986 const std::map<int32_t, PointF> expectedPointers{{1, PointF{110, 100}}};
1987 window->consumeMotionEvent(
1988 AllOf(WithMotionAction(ACTION_CANCEL), WithPointers(expectedPointers)));
1989}
1990
1991/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001992 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1993 * with the following differences:
1994 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1995 * clean up the connection.
1996 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1997 * Ensure that there's no crash in the dispatcher.
1998 */
1999TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
2000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2001 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002002 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002003 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002004 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002005 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002006 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002007
2008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
2009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2010 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2011 {100, 200}))
2012 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2013
2014 // Both foreground window and its wallpaper should receive the touch down
2015 foregroundWindow->consumeMotionDown();
2016 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2017
2018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2019 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2020 ADISPLAY_ID_DEFAULT, {110, 200}))
2021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2022
2023 foregroundWindow->consumeMotionMove();
2024 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2025
2026 // Wallpaper closes its channel, but the window remains.
2027 wallpaperWindow->destroyReceiver();
2028 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
2029
2030 // Now the foreground window goes away, but the wallpaper stays, even though its channel
2031 // is no longer valid.
2032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
2033 foregroundWindow->consumeMotionCancel();
2034}
2035
Arthur Hungc539dbb2022-12-08 07:45:36 +00002036class ShouldSplitTouchFixture : public InputDispatcherTest,
2037 public ::testing::WithParamInterface<bool> {};
2038INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
2039 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002040/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002041 * A single window that receives touch (on top), and a wallpaper window underneath it.
2042 * The top window gets a multitouch gesture.
2043 * Ensure that wallpaper gets the same gesture.
2044 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00002045TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002046 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002047 sp<FakeWindowHandle> foregroundWindow =
2048 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2049 foregroundWindow->setDupTouchToWallpaper(true);
2050 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002051
2052 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002053 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002054 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002055
Arthur Hungc539dbb2022-12-08 07:45:36 +00002056 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002057
2058 // Touch down on top window
2059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2060 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2061 {100, 100}))
2062 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2063
2064 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00002065 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002066 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2067
2068 // Second finger down on the top window
2069 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002070 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002071 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002072 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2073 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002074 .build();
2075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2076 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2077 InputEventInjectionSync::WAIT_FOR_RESULT))
2078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2079
Harry Cutts33476232023-01-30 19:57:29 +00002080 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
2081 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002082 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002083
2084 const MotionEvent secondFingerUpEvent =
2085 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2086 .displayId(ADISPLAY_ID_DEFAULT)
2087 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002088 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2089 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002090 .build();
2091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2092 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
2093 InputEventInjectionSync::WAIT_FOR_RESULT))
2094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2095 foregroundWindow->consumeMotionPointerUp(0);
2096 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2097
2098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08002099 injectMotionEvent(mDispatcher,
2100 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2101 AINPUT_SOURCE_TOUCHSCREEN)
2102 .displayId(ADISPLAY_ID_DEFAULT)
2103 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2104 .pointer(PointerBuilder(/* id */ 1,
2105 AMOTION_EVENT_TOOL_TYPE_FINGER)
2106 .x(100)
2107 .y(100))
2108 .build(),
2109 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2111 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2112 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002113}
2114
2115/**
2116 * Two windows: a window on the left and window on the right.
2117 * A third window, wallpaper, is behind both windows, and spans both top windows.
2118 * The first touch down goes to the left window. A second pointer touches down on the right window.
2119 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2120 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2121 * ACTION_POINTER_DOWN(1).
2122 */
2123TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2124 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2125 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002126 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002127 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002128 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002129
2130 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002131 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002132 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002133 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002134
2135 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002136 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002137 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002138 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002139
2140 mDispatcher->setInputWindows(
2141 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2142
2143 // Touch down on left window
2144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2145 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2146 {100, 100}))
2147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2148
2149 // Both foreground window and its wallpaper should receive the touch down
2150 leftWindow->consumeMotionDown();
2151 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2152
2153 // Second finger down on the right window
2154 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002155 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002156 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002157 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2158 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002159 .build();
2160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2161 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2162 InputEventInjectionSync::WAIT_FOR_RESULT))
2163 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2164
2165 leftWindow->consumeMotionMove();
2166 // Since the touch is split, right window gets ACTION_DOWN
2167 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002168 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002169 expectedWallpaperFlags);
2170
2171 // Now, leftWindow, which received the first finger, disappears.
2172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2173 leftWindow->consumeMotionCancel();
2174 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2175 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2176
2177 // The pointer that's still down on the right window moves, and goes to the right window only.
2178 // As far as the dispatcher's concerned though, both pointers are still present.
2179 const MotionEvent secondFingerMoveEvent =
2180 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2181 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002182 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2183 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002184 .build();
2185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2186 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2187 InputEventInjectionSync::WAIT_FOR_RESULT));
2188 rightWindow->consumeMotionMove();
2189
2190 leftWindow->assertNoEvents();
2191 rightWindow->assertNoEvents();
2192 wallpaperWindow->assertNoEvents();
2193}
2194
Arthur Hungc539dbb2022-12-08 07:45:36 +00002195/**
2196 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2197 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2198 * The right window should receive ACTION_DOWN.
2199 */
2200TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002201 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002202 sp<FakeWindowHandle> leftWindow =
2203 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2204 leftWindow->setFrame(Rect(0, 0, 200, 200));
2205 leftWindow->setDupTouchToWallpaper(true);
2206 leftWindow->setSlippery(true);
2207
2208 sp<FakeWindowHandle> rightWindow =
2209 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2210 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002211
2212 sp<FakeWindowHandle> wallpaperWindow =
2213 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2214 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002215
Arthur Hungc539dbb2022-12-08 07:45:36 +00002216 mDispatcher->setInputWindows(
2217 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002218
Arthur Hungc539dbb2022-12-08 07:45:36 +00002219 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2221 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002222 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002223 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002224
2225 // Both foreground window and its wallpaper should receive the touch down
2226 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002227 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2228
Arthur Hungc539dbb2022-12-08 07:45:36 +00002229 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002231 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2232 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002233 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2234
Arthur Hungc539dbb2022-12-08 07:45:36 +00002235 leftWindow->consumeMotionCancel();
2236 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2237 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002238}
2239
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002240/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002241 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2242 * interactive, it might stop sending this flag.
2243 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2244 * to have a consistent input stream.
2245 *
2246 * Test procedure:
2247 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2248 * DOWN (new gesture).
2249 *
2250 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2251 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2252 *
2253 * We technically just need a single window here, but we are using two windows (spy on top and a
2254 * regular window below) to emulate the actual situation where it happens on the device.
2255 */
2256TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2257 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2258 sp<FakeWindowHandle> spyWindow =
2259 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2260 spyWindow->setFrame(Rect(0, 0, 200, 200));
2261 spyWindow->setTrustedOverlay(true);
2262 spyWindow->setSpy(true);
2263
2264 sp<FakeWindowHandle> window =
2265 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2266 window->setFrame(Rect(0, 0, 200, 200));
2267
2268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2269 const int32_t touchDeviceId = 4;
2270 NotifyMotionArgs args;
2271
2272 // Two pointers down
2273 mDispatcher->notifyMotion(&(
2274 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2275 .deviceId(touchDeviceId)
2276 .policyFlags(DEFAULT_POLICY_FLAGS)
2277 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2278 .build()));
2279
2280 mDispatcher->notifyMotion(&(
2281 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2282 .deviceId(touchDeviceId)
2283 .policyFlags(DEFAULT_POLICY_FLAGS)
2284 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2285 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2286 .build()));
2287 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2288 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2289 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2290 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2291
2292 // Cancel the current gesture. Send the cancel without the default policy flags.
2293 mDispatcher->notifyMotion(&(
2294 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2295 .deviceId(touchDeviceId)
2296 .policyFlags(0)
2297 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2298 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2299 .build()));
2300 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2301 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2302
2303 // We don't need to reset the device to reproduce the issue, but the reset event typically
2304 // follows, so we keep it here to model the actual listener behaviour more closely.
2305 NotifyDeviceResetArgs resetArgs;
2306 resetArgs.id = 1; // arbitrary id
2307 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2308 resetArgs.deviceId = touchDeviceId;
2309 mDispatcher->notifyDeviceReset(&resetArgs);
2310
2311 // Start new gesture
2312 mDispatcher->notifyMotion(&(
2313 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2314 .deviceId(touchDeviceId)
2315 .policyFlags(DEFAULT_POLICY_FLAGS)
2316 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2317 .build()));
2318 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2319 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2320
2321 // No more events
2322 spyWindow->assertNoEvents();
2323 window->assertNoEvents();
2324}
2325
2326/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002327 * Two windows: a window on the left and a window on the right.
2328 * Mouse is hovered from the right window into the left window.
2329 * Next, we tap on the left window, where the cursor was last seen.
2330 * The second tap is done onto the right window.
2331 * The mouse and tap are from two different devices.
2332 * We technically don't need to set the downtime / eventtime for these events, but setting these
2333 * explicitly helps during debugging.
2334 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2335 * In the buggy implementation, a tap on the right window would cause a crash.
2336 */
2337TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2338 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2339 sp<FakeWindowHandle> leftWindow =
2340 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2341 leftWindow->setFrame(Rect(0, 0, 200, 200));
2342
2343 sp<FakeWindowHandle> rightWindow =
2344 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2345 rightWindow->setFrame(Rect(200, 0, 400, 200));
2346
2347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2348 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2349 // stale.
2350 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2351 const int32_t mouseDeviceId = 6;
2352 const int32_t touchDeviceId = 4;
2353 // Move the cursor from right
2354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2355 injectMotionEvent(mDispatcher,
2356 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2357 AINPUT_SOURCE_MOUSE)
2358 .deviceId(mouseDeviceId)
2359 .downTime(baseTime + 10)
2360 .eventTime(baseTime + 20)
2361 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2362 .x(300)
2363 .y(100))
2364 .build()));
2365 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2366
2367 // .. to the left window
2368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2369 injectMotionEvent(mDispatcher,
2370 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2371 AINPUT_SOURCE_MOUSE)
2372 .deviceId(mouseDeviceId)
2373 .downTime(baseTime + 10)
2374 .eventTime(baseTime + 30)
2375 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2376 .x(110)
2377 .y(100))
2378 .build()));
2379 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2380 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2381 // Now tap the left window
2382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2383 injectMotionEvent(mDispatcher,
2384 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2385 AINPUT_SOURCE_TOUCHSCREEN)
2386 .deviceId(touchDeviceId)
2387 .downTime(baseTime + 40)
2388 .eventTime(baseTime + 40)
2389 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2390 .x(100)
2391 .y(100))
2392 .build()));
2393 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2394 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2395
2396 // release tap
2397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2398 injectMotionEvent(mDispatcher,
2399 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2400 AINPUT_SOURCE_TOUCHSCREEN)
2401 .deviceId(touchDeviceId)
2402 .downTime(baseTime + 40)
2403 .eventTime(baseTime + 50)
2404 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2405 .x(100)
2406 .y(100))
2407 .build()));
2408 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2409
2410 // Tap the window on the right
2411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2412 injectMotionEvent(mDispatcher,
2413 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2414 AINPUT_SOURCE_TOUCHSCREEN)
2415 .deviceId(touchDeviceId)
2416 .downTime(baseTime + 60)
2417 .eventTime(baseTime + 60)
2418 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2419 .x(300)
2420 .y(100))
2421 .build()));
2422 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2423
2424 // release tap
2425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2426 injectMotionEvent(mDispatcher,
2427 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2428 AINPUT_SOURCE_TOUCHSCREEN)
2429 .deviceId(touchDeviceId)
2430 .downTime(baseTime + 60)
2431 .eventTime(baseTime + 70)
2432 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2433 .x(300)
2434 .y(100))
2435 .build()));
2436 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2437
2438 // No more events
2439 leftWindow->assertNoEvents();
2440 rightWindow->assertNoEvents();
2441}
2442
2443/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002444 * Two windows: a window on the left and a window on the right.
2445 * Mouse is clicked on the left window and remains down. Touch is touched on the right and remains
2446 * down. Then, on the left window, also place second touch pointer down.
2447 * This test tries to reproduce a crash.
2448 * In the buggy implementation, second pointer down on the left window would cause a crash.
2449 */
2450TEST_F(InputDispatcherTest, MultiDeviceSplitTouch) {
2451 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2452 sp<FakeWindowHandle> leftWindow =
2453 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2454 leftWindow->setFrame(Rect(0, 0, 200, 200));
2455
2456 sp<FakeWindowHandle> rightWindow =
2457 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2458 rightWindow->setFrame(Rect(200, 0, 400, 200));
2459
2460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2461
2462 const int32_t touchDeviceId = 4;
2463 const int32_t mouseDeviceId = 6;
2464 NotifyMotionArgs args;
2465
2466 // Start hovering over the left window
2467 mDispatcher->notifyMotion(&(
2468 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2469 .deviceId(mouseDeviceId)
2470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2471 .build()));
2472 leftWindow->consumeMotionEvent(
2473 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2474
2475 // Mouse down on left window
2476 mDispatcher->notifyMotion(&(
2477 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2478 .deviceId(mouseDeviceId)
2479 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2480 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2481 .build()));
2482
2483 leftWindow->consumeMotionEvent(
2484 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
2485 leftWindow->consumeMotionEvent(
2486 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2487
2488 mDispatcher->notifyMotion(&(
2489 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2490 .deviceId(mouseDeviceId)
2491 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2492 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2493 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2494 .build()));
2495 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2496
2497 // First touch pointer down on right window
2498 mDispatcher->notifyMotion(&(
2499 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2500 .deviceId(touchDeviceId)
2501 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2502 .build()));
2503 leftWindow->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2504
2505 rightWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2506
2507 // Second touch pointer down on left window
2508 mDispatcher->notifyMotion(&(
2509 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2510 .deviceId(touchDeviceId)
2511 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2512 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2513 .build()));
2514 leftWindow->consumeMotionEvent(
2515 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2516 // This MOVE event is not necessary (doesn't carry any new information), but it's there in the
2517 // current implementation.
2518 const std::map<int32_t, PointF> expectedPointers{{0, PointF{100, 100}}};
2519 rightWindow->consumeMotionEvent(
2520 AllOf(WithMotionAction(ACTION_MOVE), WithPointers(expectedPointers)));
2521
2522 leftWindow->assertNoEvents();
2523 rightWindow->assertNoEvents();
2524}
2525
2526/**
2527 * On a single window, use two different devices: mouse and touch.
2528 * Touch happens first, with two pointers going down, and then the first pointer leaving.
2529 * Mouse is clicked next, which causes the touch stream to be aborted with ACTION_CANCEL.
2530 * Finally, a second touch pointer goes down again. Ensure the second touch pointer is ignored,
2531 * because the mouse is currently down, and a POINTER_DOWN event from the touchscreen does not
2532 * represent a new gesture.
2533 */
2534TEST_F(InputDispatcherTest, MixedTouchAndMouseWithPointerDown) {
2535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2536 sp<FakeWindowHandle> window =
2537 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2538 window->setFrame(Rect(0, 0, 400, 400));
2539
2540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2541
2542 const int32_t touchDeviceId = 4;
2543 const int32_t mouseDeviceId = 6;
2544 NotifyMotionArgs args;
2545
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08002546 // First touch pointer down
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002547 mDispatcher->notifyMotion(&(
2548 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2549 .deviceId(touchDeviceId)
2550 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2551 .build()));
2552 // Second touch pointer down
2553 mDispatcher->notifyMotion(&(
2554 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2555 .deviceId(touchDeviceId)
2556 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2557 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2558 .build()));
2559 // First touch pointer lifts. The second one remains down
2560 mDispatcher->notifyMotion(&(
2561 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2562 .deviceId(touchDeviceId)
2563 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2564 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2565 .build()));
2566 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2567 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2568 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
2569
2570 // Mouse down. The touch should be canceled
2571 mDispatcher->notifyMotion(&(
2572 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2573 .deviceId(mouseDeviceId)
2574 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2575 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2576 .build()));
2577
2578 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08002579 WithPointerCount(1u)));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002580 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2581
2582 mDispatcher->notifyMotion(&(
2583 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2584 .deviceId(mouseDeviceId)
2585 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2586 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2587 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2588 .build()));
2589 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2590
2591 // Second touch pointer down.
2592 mDispatcher->notifyMotion(&(
2593 args = MotionArgsBuilder(POINTER_0_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2594 .deviceId(touchDeviceId)
2595 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2596 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2597 .build()));
2598 // The pointer_down event should be ignored
2599 window->assertNoEvents();
2600}
2601
2602/**
Siarhei Vishniakou56e79092023-02-21 19:13:16 -08002603 * Inject a touch down and then send a new event via 'notifyMotion'. Ensure the new event cancels
2604 * the injected event.
2605 */
2606TEST_F(InputDispatcherTest, UnfinishedInjectedEvent) {
2607 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2608 sp<FakeWindowHandle> window =
2609 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2610 window->setFrame(Rect(0, 0, 400, 400));
2611
2612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2613
2614 const int32_t touchDeviceId = 4;
2615 NotifyMotionArgs args;
2616 // Pretend a test injects an ACTION_DOWN mouse event, but forgets to lift up the touch after
2617 // completion.
2618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2619 injectMotionEvent(mDispatcher,
2620 MotionEventBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2621 .deviceId(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID)
2622 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2623 .x(50)
2624 .y(50))
2625 .build()));
2626 window->consumeMotionEvent(
2627 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2628
2629 // Now a real touch comes. Rather than crashing or dropping the real event, the injected pointer
2630 // should be canceled and the new gesture should take over.
2631 mDispatcher->notifyMotion(&(
2632 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2633 .deviceId(touchDeviceId)
2634 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2635 .build()));
2636
2637 window->consumeMotionEvent(
2638 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2639 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2640}
2641
2642/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002643 * This test is similar to the test above, but the sequence of injected events is different.
2644 *
2645 * Two windows: a window on the left and a window on the right.
2646 * Mouse is hovered over the left window.
2647 * Next, we tap on the left window, where the cursor was last seen.
2648 *
2649 * After that, we inject one finger down onto the right window, and then a second finger down onto
2650 * the left window.
2651 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2652 * window (first), and then another on the left window (second).
2653 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2654 * In the buggy implementation, second finger down on the left window would cause a crash.
2655 */
2656TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2657 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2658 sp<FakeWindowHandle> leftWindow =
2659 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2660 leftWindow->setFrame(Rect(0, 0, 200, 200));
2661
2662 sp<FakeWindowHandle> rightWindow =
2663 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2664 rightWindow->setFrame(Rect(200, 0, 400, 200));
2665
2666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2667
2668 const int32_t mouseDeviceId = 6;
2669 const int32_t touchDeviceId = 4;
2670 // Hover over the left window. Keep the cursor there.
2671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2672 injectMotionEvent(mDispatcher,
2673 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2674 AINPUT_SOURCE_MOUSE)
2675 .deviceId(mouseDeviceId)
2676 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2677 .x(50)
2678 .y(50))
2679 .build()));
2680 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2681
2682 // Tap on left window
2683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2684 injectMotionEvent(mDispatcher,
2685 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2686 AINPUT_SOURCE_TOUCHSCREEN)
2687 .deviceId(touchDeviceId)
2688 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2689 .x(100)
2690 .y(100))
2691 .build()));
2692
2693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2694 injectMotionEvent(mDispatcher,
2695 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2696 AINPUT_SOURCE_TOUCHSCREEN)
2697 .deviceId(touchDeviceId)
2698 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2699 .x(100)
2700 .y(100))
2701 .build()));
2702 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2703 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2704 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2705
2706 // First finger down on right window
2707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2708 injectMotionEvent(mDispatcher,
2709 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2710 AINPUT_SOURCE_TOUCHSCREEN)
2711 .deviceId(touchDeviceId)
2712 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2713 .x(300)
2714 .y(100))
2715 .build()));
2716 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2717
2718 // Second finger down on the left window
2719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2720 injectMotionEvent(mDispatcher,
2721 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2722 .deviceId(touchDeviceId)
2723 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2724 .x(300)
2725 .y(100))
2726 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2727 .x(100)
2728 .y(100))
2729 .build()));
2730 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2731 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2732
2733 // No more events
2734 leftWindow->assertNoEvents();
2735 rightWindow->assertNoEvents();
2736}
2737
2738/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002739 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2740 * While the touch is down, new hover events from the stylus device should be ignored. After the
2741 * touch is gone, stylus hovering should start working again.
2742 */
2743TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2745 sp<FakeWindowHandle> window =
2746 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2747 window->setFrame(Rect(0, 0, 200, 200));
2748
2749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2750
2751 const int32_t stylusDeviceId = 5;
2752 const int32_t touchDeviceId = 4;
2753 // Start hovering with stylus
2754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2755 injectMotionEvent(mDispatcher,
2756 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2757 AINPUT_SOURCE_STYLUS)
2758 .deviceId(stylusDeviceId)
2759 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2760 .x(50)
2761 .y(50))
2762 .build()));
2763 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2764
2765 // Finger down on the window
2766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2767 injectMotionEvent(mDispatcher,
2768 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2769 AINPUT_SOURCE_TOUCHSCREEN)
2770 .deviceId(touchDeviceId)
2771 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2772 .x(100)
2773 .y(100))
2774 .build()));
2775 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2776 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2777
2778 // Try to continue hovering with stylus. Since we are already down, injection should fail
2779 ASSERT_EQ(InputEventInjectionResult::FAILED,
2780 injectMotionEvent(mDispatcher,
2781 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2782 AINPUT_SOURCE_STYLUS)
2783 .deviceId(stylusDeviceId)
2784 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2785 .x(50)
2786 .y(50))
2787 .build()));
2788 // No event should be sent. This event should be ignored because a pointer from another device
2789 // is already down.
2790
2791 // Lift up the finger
2792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2793 injectMotionEvent(mDispatcher,
2794 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2795 AINPUT_SOURCE_TOUCHSCREEN)
2796 .deviceId(touchDeviceId)
2797 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2798 .x(100)
2799 .y(100))
2800 .build()));
2801 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2802
2803 // Now that the touch is gone, stylus hovering should start working again
2804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2805 injectMotionEvent(mDispatcher,
2806 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2807 AINPUT_SOURCE_STYLUS)
2808 .deviceId(stylusDeviceId)
2809 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2810 .x(50)
2811 .y(50))
2812 .build()));
2813 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2814 // No more events
2815 window->assertNoEvents();
2816}
2817
2818/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002819 * A spy window above a window with no input channel.
2820 * Start hovering with a stylus device, and then tap with it.
2821 * Ensure spy window receives the entire sequence.
2822 */
2823TEST_F(InputDispatcherTest, StylusHoverAndDownNoInputChannel) {
2824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2825 sp<FakeWindowHandle> spyWindow =
2826 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2827 spyWindow->setFrame(Rect(0, 0, 200, 200));
2828 spyWindow->setTrustedOverlay(true);
2829 spyWindow->setSpy(true);
2830 sp<FakeWindowHandle> window =
2831 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2832 window->setNoInputChannel(true);
2833 window->setFrame(Rect(0, 0, 200, 200));
2834
2835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2836
2837 NotifyMotionArgs args;
2838
2839 // Start hovering with stylus
2840 mDispatcher->notifyMotion(
2841 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2842 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2843 .build()));
2844 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2845 // Stop hovering
2846 mDispatcher->notifyMotion(
2847 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2848 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2849 .build()));
2850 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2851
2852 // Stylus touches down
2853 mDispatcher->notifyMotion(
2854 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_STYLUS)
2855 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2856 .build()));
2857 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2858
2859 // Stylus goes up
2860 mDispatcher->notifyMotion(
2861 &(args = MotionArgsBuilder(ACTION_UP, AINPUT_SOURCE_STYLUS)
2862 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2863 .build()));
2864 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_UP));
2865
2866 // Again hover
2867 mDispatcher->notifyMotion(
2868 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2869 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2870 .build()));
2871 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2872 // Stop hovering
2873 mDispatcher->notifyMotion(
2874 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2876 .build()));
2877 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2878
2879 // No more events
2880 spyWindow->assertNoEvents();
2881 window->assertNoEvents();
2882}
2883
2884/**
2885 * Start hovering with a mouse, and then tap with a touch device. Pilfer the touch stream.
2886 * Next, click with the mouse device. Both windows (spy and regular) should receive the new mouse
2887 * ACTION_DOWN event because that's a new gesture, and pilfering should no longer be active.
2888 * While the mouse is down, new move events from the touch device should be ignored.
2889 */
2890TEST_F(InputDispatcherTest, TouchPilferAndMouseMove) {
2891 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2892 sp<FakeWindowHandle> spyWindow =
2893 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2894 spyWindow->setFrame(Rect(0, 0, 200, 200));
2895 spyWindow->setTrustedOverlay(true);
2896 spyWindow->setSpy(true);
2897 sp<FakeWindowHandle> window =
2898 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2899 window->setFrame(Rect(0, 0, 200, 200));
2900
2901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2902
2903 const int32_t mouseDeviceId = 7;
2904 const int32_t touchDeviceId = 4;
2905 NotifyMotionArgs args;
2906
2907 // Hover a bit with mouse first
2908 mDispatcher->notifyMotion(&(
2909 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2910 .deviceId(mouseDeviceId)
2911 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2912 .build()));
2913 spyWindow->consumeMotionEvent(
2914 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2915 window->consumeMotionEvent(
2916 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2917
2918 // Start touching
2919 mDispatcher->notifyMotion(
2920 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2921 .deviceId(touchDeviceId)
2922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2923 .build()));
2924 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2925 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2926 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2927 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2928
2929 mDispatcher->notifyMotion(
2930 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2931 .deviceId(touchDeviceId)
2932 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(55).y(55))
2933 .build()));
2934 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2935 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2936
2937 // Pilfer the stream
2938 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2939 window->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2940
2941 mDispatcher->notifyMotion(
2942 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2943 .deviceId(touchDeviceId)
2944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
2945 .build()));
2946 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2947
2948 // Mouse down
2949 mDispatcher->notifyMotion(&(
2950 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2951 .deviceId(mouseDeviceId)
2952 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2953 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2954 .build()));
2955
2956 spyWindow->consumeMotionEvent(
2957 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId)));
2958 spyWindow->consumeMotionEvent(
2959 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2960 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2961
2962 mDispatcher->notifyMotion(&(
2963 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2964 .deviceId(mouseDeviceId)
2965 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2966 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2967 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2968 .build()));
2969 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2970 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2971
2972 // Mouse move!
2973 mDispatcher->notifyMotion(&(
2974 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_MOUSE)
2975 .deviceId(mouseDeviceId)
2976 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(110).y(110))
2978 .build()));
2979 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2980 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2981
2982 // Touch move!
2983 mDispatcher->notifyMotion(
2984 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2985 .deviceId(touchDeviceId)
2986 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(65).y(65))
2987 .build()));
2988
2989 // No more events
2990 spyWindow->assertNoEvents();
2991 window->assertNoEvents();
2992}
2993
2994/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002995 * On the display, have a single window, and also an area where there's no window.
2996 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2997 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2998 */
2999TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
3000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3001 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003002 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003003
3004 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
3005 NotifyMotionArgs args;
3006
3007 // Touch down on the empty space
3008 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
3009
3010 mDispatcher->waitForIdle();
3011 window->assertNoEvents();
3012
3013 // Now touch down on the window with another pointer
3014 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
3015 mDispatcher->waitForIdle();
3016 window->consumeMotionDown();
3017}
3018
3019/**
3020 * Same test as above, but instead of touching the empty space, the first touch goes to
3021 * non-touchable window.
3022 */
3023TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
3024 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3025 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003026 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003027 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3028 window1->setTouchable(false);
3029 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003030 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003031 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3032
3033 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3034
3035 NotifyMotionArgs args;
3036 // Touch down on the non-touchable window
3037 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3038
3039 mDispatcher->waitForIdle();
3040 window1->assertNoEvents();
3041 window2->assertNoEvents();
3042
3043 // Now touch down on the window with another pointer
3044 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3045 mDispatcher->waitForIdle();
3046 window2->consumeMotionDown();
3047}
3048
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003049/**
3050 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
3051 * to the event time of the first ACTION_DOWN sent to the particular window.
3052 */
3053TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
3054 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3055 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003056 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003057 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3058 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003059 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003060 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3061
3062 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3063
3064 NotifyMotionArgs args;
3065 // Touch down on the first window
3066 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3067
3068 mDispatcher->waitForIdle();
3069 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003070 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003071 window2->assertNoEvents();
3072 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
3073 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
3074 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
3075
3076 // Now touch down on the window with another pointer
3077 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3078 mDispatcher->waitForIdle();
3079 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003080 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003081 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
3082 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
3083 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
3084 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
3085
3086 // Now move the pointer on the second window
3087 mDispatcher->notifyMotion(
3088 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
3089 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003090 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003091
3092 // Now add new touch down on the second window
3093 mDispatcher->notifyMotion(
3094 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
3095 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003096 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003097
3098 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
3099 window1->consumeMotionMove();
3100 window1->assertNoEvents();
3101
3102 // Now move the pointer on the first window
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08003103 mDispatcher->notifyMotion(&(
3104 args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}, {150, 50}})));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003105 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003106 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003107
3108 mDispatcher->notifyMotion(&(
3109 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
3110 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003111 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003112}
3113
Garfield Tandf26e862020-07-01 20:18:19 -07003114TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003116 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003117 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003118 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003119 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003120 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003121 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003122
3123 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3124
3125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
3126
3127 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003129 injectMotionEvent(mDispatcher,
3130 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3131 AINPUT_SOURCE_MOUSE)
3132 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3133 .x(900)
3134 .y(400))
3135 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003136 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003137
3138 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003140 injectMotionEvent(mDispatcher,
3141 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3142 AINPUT_SOURCE_MOUSE)
3143 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3144 .x(300)
3145 .y(400))
3146 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003147 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3148 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003149
3150 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003152 injectMotionEvent(mDispatcher,
3153 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3154 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3155 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3156 .x(300)
3157 .y(400))
3158 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003159 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3160 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003161
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003163 injectMotionEvent(mDispatcher,
3164 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3165 AINPUT_SOURCE_MOUSE)
3166 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3167 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3168 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3169 .x(300)
3170 .y(400))
3171 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003172 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003174 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003175 injectMotionEvent(mDispatcher,
3176 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3177 AINPUT_SOURCE_MOUSE)
3178 .buttonState(0)
3179 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3180 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3181 .x(300)
3182 .y(400))
3183 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003184 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003187 injectMotionEvent(mDispatcher,
3188 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3189 .buttonState(0)
3190 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3191 .x(300)
3192 .y(400))
3193 .build()));
3194 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3195
3196 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003198 injectMotionEvent(mDispatcher,
3199 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3200 AINPUT_SOURCE_MOUSE)
3201 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3202 .x(900)
3203 .y(400))
3204 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003205 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003206
3207 // No more events
3208 windowLeft->assertNoEvents();
3209 windowRight->assertNoEvents();
3210}
3211
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003212/**
3213 * Put two fingers down (and don't release them) and click the mouse button.
3214 * The clicking of mouse is a new ACTION_DOWN event. Since it's from a different device, the
3215 * currently active gesture should be canceled, and the new one should proceed.
3216 */
3217TEST_F(InputDispatcherTest, TwoPointersDownMouseClick) {
3218 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3219 sp<FakeWindowHandle> window =
3220 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3221 window->setFrame(Rect(0, 0, 600, 800));
3222
3223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3224
3225 const int32_t touchDeviceId = 4;
3226 const int32_t mouseDeviceId = 6;
3227 NotifyMotionArgs args;
3228
3229 // Two pointers down
3230 mDispatcher->notifyMotion(&(
3231 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3232 .deviceId(touchDeviceId)
3233 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3234 .build()));
3235
3236 mDispatcher->notifyMotion(&(
3237 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3238 .deviceId(touchDeviceId)
3239 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3240 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
3241 .build()));
3242 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
3243 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
3244
3245 // Inject a series of mouse events for a mouse click
3246 mDispatcher->notifyMotion(&(
3247 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3248 .deviceId(mouseDeviceId)
3249 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3250 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3251 .build()));
3252 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
3253 WithPointerCount(2u)));
3254 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
3255
3256 mDispatcher->notifyMotion(&(
3257 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
3258 .deviceId(mouseDeviceId)
3259 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3260 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3261 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3262 .build()));
3263 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
3264
3265 // Try to send more touch events while the mouse is down. Since it's a continuation of an
3266 // already canceled gesture, it should be ignored.
3267 mDispatcher->notifyMotion(&(
3268 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
3269 .deviceId(touchDeviceId)
3270 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(101).y(101))
3271 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(121).y(121))
3272 .build()));
3273 window->assertNoEvents();
3274}
3275
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003276TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
3277 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3278
3279 sp<FakeWindowHandle> spyWindow =
3280 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3281 spyWindow->setFrame(Rect(0, 0, 600, 800));
3282 spyWindow->setTrustedOverlay(true);
3283 spyWindow->setSpy(true);
3284 sp<FakeWindowHandle> window =
3285 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3286 window->setFrame(Rect(0, 0, 600, 800));
3287
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3290
3291 // Send mouse cursor to the window
3292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3293 injectMotionEvent(mDispatcher,
3294 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3295 AINPUT_SOURCE_MOUSE)
3296 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3297 .x(100)
3298 .y(100))
3299 .build()));
3300
3301 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3302 WithSource(AINPUT_SOURCE_MOUSE)));
3303 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3304 WithSource(AINPUT_SOURCE_MOUSE)));
3305
3306 window->assertNoEvents();
3307 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003308}
3309
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003310TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
3311 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3312
3313 sp<FakeWindowHandle> spyWindow =
3314 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3315 spyWindow->setFrame(Rect(0, 0, 600, 800));
3316 spyWindow->setTrustedOverlay(true);
3317 spyWindow->setSpy(true);
3318 sp<FakeWindowHandle> window =
3319 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3320 window->setFrame(Rect(0, 0, 600, 800));
3321
3322 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3324
3325 // Send mouse cursor to the window
3326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3327 injectMotionEvent(mDispatcher,
3328 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3329 AINPUT_SOURCE_MOUSE)
3330 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3331 .x(100)
3332 .y(100))
3333 .build()));
3334
3335 // Move mouse cursor
3336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3337 injectMotionEvent(mDispatcher,
3338 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3339 AINPUT_SOURCE_MOUSE)
3340 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3341 .x(110)
3342 .y(110))
3343 .build()));
3344
3345 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3346 WithSource(AINPUT_SOURCE_MOUSE)));
3347 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3348 WithSource(AINPUT_SOURCE_MOUSE)));
3349 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3350 WithSource(AINPUT_SOURCE_MOUSE)));
3351 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3352 WithSource(AINPUT_SOURCE_MOUSE)));
3353 // Touch down on the window
3354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3355 injectMotionEvent(mDispatcher,
3356 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3357 AINPUT_SOURCE_TOUCHSCREEN)
3358 .deviceId(SECOND_DEVICE_ID)
3359 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3360 .x(200)
3361 .y(200))
3362 .build()));
3363 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3364 WithSource(AINPUT_SOURCE_MOUSE)));
3365 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3366 WithSource(AINPUT_SOURCE_MOUSE)));
3367 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3368 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3369 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3370 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3371
3372 // pilfer the motion, retaining the gesture on the spy window.
3373 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
3374 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3375 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3376
3377 // Touch UP on the window
3378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3379 injectMotionEvent(mDispatcher,
3380 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3381 AINPUT_SOURCE_TOUCHSCREEN)
3382 .deviceId(SECOND_DEVICE_ID)
3383 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3384 .x(200)
3385 .y(200))
3386 .build()));
3387 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3388 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3389
3390 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
3391 // to send a new gesture. It should again go to both windows (spy and the window below), just
3392 // like the first gesture did, before pilfering. The window configuration has not changed.
3393
3394 // One more tap - DOWN
3395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3396 injectMotionEvent(mDispatcher,
3397 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3398 AINPUT_SOURCE_TOUCHSCREEN)
3399 .deviceId(SECOND_DEVICE_ID)
3400 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3401 .x(250)
3402 .y(250))
3403 .build()));
3404 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3405 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3406 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3407 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3408
3409 // Touch UP on the window
3410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3411 injectMotionEvent(mDispatcher,
3412 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3413 AINPUT_SOURCE_TOUCHSCREEN)
3414 .deviceId(SECOND_DEVICE_ID)
3415 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3416 .x(250)
3417 .y(250))
3418 .build()));
3419 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3420 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3421 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3422 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3423
3424 window->assertNoEvents();
3425 spyWindow->assertNoEvents();
3426}
3427
Garfield Tandf26e862020-07-01 20:18:19 -07003428// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
3429// directly in this test.
3430TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003431 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003432 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003433 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003434 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003435
3436 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3437
3438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003441 injectMotionEvent(mDispatcher,
3442 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3443 AINPUT_SOURCE_MOUSE)
3444 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3445 .x(300)
3446 .y(400))
3447 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003448 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003449 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003451 injectMotionEvent(mDispatcher,
3452 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3453 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3454 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3455 .x(300)
3456 .y(400))
3457 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003458 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3459 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003462 injectMotionEvent(mDispatcher,
3463 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3464 AINPUT_SOURCE_MOUSE)
3465 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3466 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3467 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3468 .x(300)
3469 .y(400))
3470 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003471 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003472
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003474 injectMotionEvent(mDispatcher,
3475 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3476 AINPUT_SOURCE_MOUSE)
3477 .buttonState(0)
3478 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3479 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3480 .x(300)
3481 .y(400))
3482 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003483 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003484
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003486 injectMotionEvent(mDispatcher,
3487 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3488 .buttonState(0)
3489 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3490 .x(300)
3491 .y(400))
3492 .build()));
3493 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3494
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003495 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003496 injectMotionEvent(mDispatcher,
3497 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
3498 AINPUT_SOURCE_MOUSE)
3499 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3500 .x(300)
3501 .y(400))
3502 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003503 window->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003504}
3505
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003506/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003507 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
3508 * is generated.
3509 */
3510TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
3511 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3512 sp<FakeWindowHandle> window =
3513 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3514 window->setFrame(Rect(0, 0, 1200, 800));
3515
3516 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3517
3518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3519
3520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3521 injectMotionEvent(mDispatcher,
3522 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3523 AINPUT_SOURCE_MOUSE)
3524 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3525 .x(300)
3526 .y(400))
3527 .build()));
3528 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3529
3530 // Remove the window, but keep the channel.
3531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3532 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3533}
3534
3535/**
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003536 * If mouse is hovering when the touch goes down, the hovering should be stopped via HOVER_EXIT.
3537 */
3538TEST_F(InputDispatcherTest, TouchDownAfterMouseHover) {
3539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3540 sp<FakeWindowHandle> window =
3541 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3542 window->setFrame(Rect(0, 0, 100, 100));
3543
3544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3545
3546 const int32_t mouseDeviceId = 7;
3547 const int32_t touchDeviceId = 4;
3548 NotifyMotionArgs args;
3549
3550 // Start hovering with the mouse
3551 mDispatcher->notifyMotion(
3552 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
3553 .deviceId(mouseDeviceId)
3554 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(10).y(10))
3555 .build()));
3556 window->consumeMotionEvent(
3557 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
3558
3559 // Touch goes down
3560 mDispatcher->notifyMotion(
3561 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3562 .deviceId(touchDeviceId)
3563 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3564 .build()));
3565
3566 window->consumeMotionEvent(
3567 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
3568 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
3569}
3570
3571/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003572 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003573 * The tap causes a HOVER_EXIT event to be generated because the current event
3574 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003575 */
3576TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3577 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3578 sp<FakeWindowHandle> window =
3579 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3580 window->setFrame(Rect(0, 0, 100, 100));
3581
3582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3583
3584 // Inject a hover_move from mouse.
3585 NotifyMotionArgs motionArgs =
3586 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3587 ADISPLAY_ID_DEFAULT, {{50, 50}});
3588 motionArgs.xCursorPosition = 50;
3589 motionArgs.yCursorPosition = 50;
3590 mDispatcher->notifyMotion(&motionArgs);
3591 ASSERT_NO_FATAL_FAILURE(
3592 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3593 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003594
3595 // Tap on the window
3596 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3597 ADISPLAY_ID_DEFAULT, {{10, 10}});
3598 mDispatcher->notifyMotion(&motionArgs);
3599 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003600 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3601 WithSource(AINPUT_SOURCE_MOUSE))));
3602
3603 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003604 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3605 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3606
3607 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3608 ADISPLAY_ID_DEFAULT, {{10, 10}});
3609 mDispatcher->notifyMotion(&motionArgs);
3610 ASSERT_NO_FATAL_FAILURE(
3611 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3612 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3613}
3614
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003615TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3617 sp<FakeWindowHandle> windowDefaultDisplay =
3618 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3619 ADISPLAY_ID_DEFAULT);
3620 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3621 sp<FakeWindowHandle> windowSecondDisplay =
3622 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3623 SECOND_DISPLAY_ID);
3624 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3625
3626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3627 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3628
3629 // Set cursor position in window in default display and check that hover enter and move
3630 // events are generated.
3631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3632 injectMotionEvent(mDispatcher,
3633 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3634 AINPUT_SOURCE_MOUSE)
3635 .displayId(ADISPLAY_ID_DEFAULT)
3636 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3637 .x(300)
3638 .y(600))
3639 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003640 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003641
3642 // Remove all windows in secondary display and check that no event happens on window in
3643 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003644 mDispatcher->setInputWindows(
3645 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003646 windowDefaultDisplay->assertNoEvents();
3647
3648 // Move cursor position in window in default display and check that only hover move
3649 // event is generated and not hover enter event.
3650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3651 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3653 injectMotionEvent(mDispatcher,
3654 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3655 AINPUT_SOURCE_MOUSE)
3656 .displayId(ADISPLAY_ID_DEFAULT)
3657 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3658 .x(400)
3659 .y(700))
3660 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003661 windowDefaultDisplay->consumeMotionEvent(
3662 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3663 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003664 windowDefaultDisplay->assertNoEvents();
3665}
3666
Garfield Tan00f511d2019-06-12 16:55:40 -07003667TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003669
3670 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003671 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003672 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003673 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003674 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003675 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003676
3677 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3678
Arthur Hung72d8dc32020-03-28 00:48:39 +00003679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003680
3681 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3682 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003684 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003685 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003686 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003687 windowRight->assertNoEvents();
3688}
3689
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003690TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003691 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003692 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3693 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003694 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003695
Arthur Hung72d8dc32020-03-28 00:48:39 +00003696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003697 setFocusedWindow(window);
3698
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003699 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003700
3701 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3702 mDispatcher->notifyKey(&keyArgs);
3703
3704 // Window should receive key down event.
3705 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3706
3707 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3708 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003709 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003710 mDispatcher->notifyDeviceReset(&args);
3711 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3712 AKEY_EVENT_FLAG_CANCELED);
3713}
3714
3715TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003716 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003717 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3718 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003719
Arthur Hung72d8dc32020-03-28 00:48:39 +00003720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003721
3722 NotifyMotionArgs motionArgs =
3723 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3724 ADISPLAY_ID_DEFAULT);
3725 mDispatcher->notifyMotion(&motionArgs);
3726
3727 // Window should receive motion down event.
3728 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3729
3730 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3731 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003732 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003733 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003734 window->consumeMotionEvent(
3735 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003736}
3737
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003738TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003740 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3741 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003742 window->setFocusable(true);
3743
3744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3745 setFocusedWindow(window);
3746
3747 window->consumeFocusEvent(true);
3748
3749 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3750 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3751 const nsecs_t injectTime = keyArgs.eventTime;
3752 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3753 mDispatcher->notifyKey(&keyArgs);
3754 // The dispatching time should be always greater than or equal to intercept key timeout.
3755 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3756 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3757 std::chrono::nanoseconds(interceptKeyTimeout).count());
3758}
3759
3760TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003762 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3763 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003764 window->setFocusable(true);
3765
3766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3767 setFocusedWindow(window);
3768
3769 window->consumeFocusEvent(true);
3770
3771 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3772 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3773 mFakePolicy->setInterceptKeyTimeout(150ms);
3774 mDispatcher->notifyKey(&keyDown);
3775 mDispatcher->notifyKey(&keyUp);
3776
3777 // Window should receive key event immediately when same key up.
3778 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3779 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3780}
3781
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003782/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003783 * Two windows. First is a regular window. Second does not overlap with the first, and has
3784 * WATCH_OUTSIDE_TOUCH.
3785 * Both windows are owned by the same UID.
3786 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3787 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3788 */
3789TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3790 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3791 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3792 "First Window", ADISPLAY_ID_DEFAULT);
3793 window->setFrame(Rect{0, 0, 100, 100});
3794
3795 sp<FakeWindowHandle> outsideWindow =
3796 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3797 ADISPLAY_ID_DEFAULT);
3798 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3799 outsideWindow->setWatchOutsideTouch(true);
3800 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3802
3803 // Tap on first window.
3804 NotifyMotionArgs motionArgs =
3805 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3806 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3807 mDispatcher->notifyMotion(&motionArgs);
3808 window->consumeMotionDown();
3809 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3810 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3811 outsideWindow->consumeMotionEvent(
3812 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3813}
3814
3815/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003816 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3817 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3818 * ACTION_OUTSIDE event is sent per gesture.
3819 */
3820TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3821 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003823 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3824 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003825 window->setWatchOutsideTouch(true);
3826 window->setFrame(Rect{0, 0, 100, 100});
3827 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003828 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3829 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003830 secondWindow->setFrame(Rect{100, 100, 200, 200});
3831 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003832 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3833 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003834 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3836
3837 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3838 NotifyMotionArgs motionArgs =
3839 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3840 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3841 mDispatcher->notifyMotion(&motionArgs);
3842 window->assertNoEvents();
3843 secondWindow->assertNoEvents();
3844
3845 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3846 // Now, `window` should get ACTION_OUTSIDE.
3847 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3848 {PointF{-10, -10}, PointF{105, 105}});
3849 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003850 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3851 window->consumeMotionEvent(
3852 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003853 secondWindow->consumeMotionDown();
3854 thirdWindow->assertNoEvents();
3855
3856 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3857 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3858 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3859 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3860 mDispatcher->notifyMotion(&motionArgs);
3861 window->assertNoEvents();
3862 secondWindow->consumeMotionMove();
3863 thirdWindow->consumeMotionDown();
3864}
3865
Prabir Pradhan814fe082022-07-22 20:22:18 +00003866TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003868 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3869 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003870 window->setFocusable(true);
3871
3872 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3873 setFocusedWindow(window);
3874
3875 window->consumeFocusEvent(true);
3876
3877 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3878 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3879 mDispatcher->notifyKey(&keyDown);
3880 mDispatcher->notifyKey(&keyUp);
3881
3882 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3883 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3884
3885 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3886 mDispatcher->onWindowInfosChanged({}, {});
3887
3888 window->consumeFocusEvent(false);
3889
3890 mDispatcher->notifyKey(&keyDown);
3891 mDispatcher->notifyKey(&keyUp);
3892 window->assertNoEvents();
3893}
3894
Arthur Hung96483742022-11-15 03:30:48 +00003895TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3897 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3898 "Fake Window", ADISPLAY_ID_DEFAULT);
3899 // Ensure window is non-split and have some transform.
3900 window->setPreventSplitting(true);
3901 window->setWindowOffset(20, 40);
3902 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3903
3904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3906 {50, 50}))
3907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3908 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3909
3910 const MotionEvent secondFingerDownEvent =
3911 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3912 .displayId(ADISPLAY_ID_DEFAULT)
3913 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003914 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3915 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003916 .build();
3917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3918 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3919 InputEventInjectionSync::WAIT_FOR_RESULT))
3920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3921
3922 const MotionEvent* event = window->consumeMotion();
3923 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3924 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3925 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3926 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3927 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3928}
3929
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003930/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003931 * Ensure the correct coordinate spaces are used by InputDispatcher.
3932 *
3933 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3934 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3935 * space.
3936 */
3937class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3938public:
3939 void SetUp() override {
3940 InputDispatcherTest::SetUp();
3941 mDisplayInfos.clear();
3942 mWindowInfos.clear();
3943 }
3944
3945 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3946 gui::DisplayInfo info;
3947 info.displayId = displayId;
3948 info.transform = transform;
3949 mDisplayInfos.push_back(std::move(info));
3950 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3951 }
3952
3953 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3954 mWindowInfos.push_back(*windowHandle->getInfo());
3955 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3956 }
3957
3958 // Set up a test scenario where the display has a scaled projection and there are two windows
3959 // on the display.
3960 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3961 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3962 // respectively.
3963 ui::Transform displayTransform;
3964 displayTransform.set(2, 0, 0, 4);
3965 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3966
3967 std::shared_ptr<FakeApplicationHandle> application =
3968 std::make_shared<FakeApplicationHandle>();
3969
3970 // Add two windows to the display. Their frames are represented in the display space.
3971 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003972 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3973 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003974 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3975 addWindow(firstWindow);
3976
3977 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003978 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3979 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003980 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3981 addWindow(secondWindow);
3982 return {std::move(firstWindow), std::move(secondWindow)};
3983 }
3984
3985private:
3986 std::vector<gui::DisplayInfo> mDisplayInfos;
3987 std::vector<gui::WindowInfo> mWindowInfos;
3988};
3989
3990TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3991 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3992 // Send down to the first window. The point is represented in the display space. The point is
3993 // selected so that if the hit test was done with the transform applied to it, then it would
3994 // end up in the incorrect window.
3995 NotifyMotionArgs downMotionArgs =
3996 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3997 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3998 mDispatcher->notifyMotion(&downMotionArgs);
3999
4000 firstWindow->consumeMotionDown();
4001 secondWindow->assertNoEvents();
4002}
4003
4004// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
4005// the event should be treated as being in the logical display space.
4006TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
4007 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4008 // Send down to the first window. The point is represented in the logical display space. The
4009 // point is selected so that if the hit test was done in logical display space, then it would
4010 // end up in the incorrect window.
4011 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4012 PointF{75 * 2, 55 * 4});
4013
4014 firstWindow->consumeMotionDown();
4015 secondWindow->assertNoEvents();
4016}
4017
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004018// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
4019// event should be treated as being in the logical display space.
4020TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
4021 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4022
4023 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
4024 ui::Transform injectedEventTransform;
4025 injectedEventTransform.set(matrix);
4026 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
4027 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
4028
4029 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
4030 .displayId(ADISPLAY_ID_DEFAULT)
4031 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00004032 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004033 .x(untransformedPoint.x)
4034 .y(untransformedPoint.y))
4035 .build();
4036 event.transform(matrix);
4037
4038 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
4039 InputEventInjectionSync::WAIT_FOR_RESULT);
4040
4041 firstWindow->consumeMotionDown();
4042 secondWindow->assertNoEvents();
4043}
4044
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07004045TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
4046 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4047
4048 // Send down to the second window.
4049 NotifyMotionArgs downMotionArgs =
4050 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4051 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
4052 mDispatcher->notifyMotion(&downMotionArgs);
4053
4054 firstWindow->assertNoEvents();
4055 const MotionEvent* event = secondWindow->consumeMotion();
4056 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
4057
4058 // Ensure that the events from the "getRaw" API are in logical display coordinates.
4059 EXPECT_EQ(300, event->getRawX(0));
4060 EXPECT_EQ(880, event->getRawY(0));
4061
4062 // Ensure that the x and y values are in the window's coordinate space.
4063 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
4064 // the logical display space. This will be the origin of the window space.
4065 EXPECT_EQ(100, event->getX(0));
4066 EXPECT_EQ(80, event->getY(0));
4067}
4068
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004069using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
4070 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004071
4072class TransferTouchFixture : public InputDispatcherTest,
4073 public ::testing::WithParamInterface<TransferFunction> {};
4074
4075TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07004076 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004077
4078 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004079 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004080 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4081 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004082 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004083 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004084 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4085 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004086 sp<FakeWindowHandle> wallpaper =
4087 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
4088 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004089 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00004090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091
4092 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004093 NotifyMotionArgs downMotionArgs =
4094 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4095 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004097
Svet Ganov5d3bc372020-01-26 23:11:07 -08004098 // Only the first window should get the down event
4099 firstWindow->consumeMotionDown();
4100 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004101 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004102
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004103 // Transfer touch to the second window
4104 TransferFunction f = GetParam();
4105 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4106 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004107 // The first window gets cancel and the second gets down
4108 firstWindow->consumeMotionCancel();
4109 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004110 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004111
4112 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004113 NotifyMotionArgs upMotionArgs =
4114 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4115 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004116 mDispatcher->notifyMotion(&upMotionArgs);
4117 // The first window gets no events and the second gets up
4118 firstWindow->assertNoEvents();
4119 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004120 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004121}
4122
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004123/**
4124 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4125 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4126 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4127 * natural to the user.
4128 * In this test, we are sending a pointer to both spy window and first window. We then try to
4129 * transfer touch to the second window. The dispatcher should identify the first window as the
4130 * one that should lose the gesture, and therefore the action should be to move the gesture from
4131 * the first window to the second.
4132 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4133 * the other API, as well.
4134 */
4135TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4136 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4137
4138 // Create a couple of windows + a spy window
4139 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004140 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004141 spyWindow->setTrustedOverlay(true);
4142 spyWindow->setSpy(true);
4143 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004144 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004145 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004146 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004147
4148 // Add the windows to the dispatcher
4149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4150
4151 // Send down to the first window
4152 NotifyMotionArgs downMotionArgs =
4153 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4154 ADISPLAY_ID_DEFAULT);
4155 mDispatcher->notifyMotion(&downMotionArgs);
4156 // Only the first window and spy should get the down event
4157 spyWindow->consumeMotionDown();
4158 firstWindow->consumeMotionDown();
4159
4160 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4161 // if f === 'transferTouch'.
4162 TransferFunction f = GetParam();
4163 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4164 ASSERT_TRUE(success);
4165 // The first window gets cancel and the second gets down
4166 firstWindow->consumeMotionCancel();
4167 secondWindow->consumeMotionDown();
4168
4169 // Send up event to the second window
4170 NotifyMotionArgs upMotionArgs =
4171 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4172 ADISPLAY_ID_DEFAULT);
4173 mDispatcher->notifyMotion(&upMotionArgs);
4174 // The first window gets no events and the second+spy get up
4175 firstWindow->assertNoEvents();
4176 spyWindow->consumeMotionUp();
4177 secondWindow->consumeMotionUp();
4178}
4179
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004180TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004181 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004182
4183 PointF touchPoint = {10, 10};
4184
4185 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004186 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004187 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4188 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004189 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004190 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004191 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4192 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004193 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004194
4195 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197
4198 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004199 NotifyMotionArgs downMotionArgs =
4200 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4201 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004202 mDispatcher->notifyMotion(&downMotionArgs);
4203 // Only the first window should get the down event
4204 firstWindow->consumeMotionDown();
4205 secondWindow->assertNoEvents();
4206
4207 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004208 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004209 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004210 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4212 // Only the first window should get the pointer down event
4213 firstWindow->consumeMotionPointerDown(1);
4214 secondWindow->assertNoEvents();
4215
4216 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004217 TransferFunction f = GetParam();
4218 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4219 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004220 // The first window gets cancel and the second gets down and pointer down
4221 firstWindow->consumeMotionCancel();
4222 secondWindow->consumeMotionDown();
4223 secondWindow->consumeMotionPointerDown(1);
4224
4225 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004226 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004227 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004228 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004229 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4230 // The first window gets nothing and the second gets pointer up
4231 firstWindow->assertNoEvents();
4232 secondWindow->consumeMotionPointerUp(1);
4233
4234 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004235 NotifyMotionArgs upMotionArgs =
4236 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4237 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238 mDispatcher->notifyMotion(&upMotionArgs);
4239 // The first window gets nothing and the second gets up
4240 firstWindow->assertNoEvents();
4241 secondWindow->consumeMotionUp();
4242}
4243
Arthur Hungc539dbb2022-12-08 07:45:36 +00004244TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4246
4247 // Create a couple of windows
4248 sp<FakeWindowHandle> firstWindow =
4249 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4250 ADISPLAY_ID_DEFAULT);
4251 firstWindow->setDupTouchToWallpaper(true);
4252 sp<FakeWindowHandle> secondWindow =
4253 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4254 ADISPLAY_ID_DEFAULT);
4255 secondWindow->setDupTouchToWallpaper(true);
4256
4257 sp<FakeWindowHandle> wallpaper1 =
4258 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4259 wallpaper1->setIsWallpaper(true);
4260
4261 sp<FakeWindowHandle> wallpaper2 =
4262 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4263 wallpaper2->setIsWallpaper(true);
4264 // Add the windows to the dispatcher
4265 mDispatcher->setInputWindows(
4266 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4267
4268 // Send down to the first window
4269 NotifyMotionArgs downMotionArgs =
4270 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4271 ADISPLAY_ID_DEFAULT);
4272 mDispatcher->notifyMotion(&downMotionArgs);
4273
4274 // Only the first window should get the down event
4275 firstWindow->consumeMotionDown();
4276 secondWindow->assertNoEvents();
4277 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4278 wallpaper2->assertNoEvents();
4279
4280 // Transfer touch focus to the second window
4281 TransferFunction f = GetParam();
4282 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4283 ASSERT_TRUE(success);
4284
4285 // The first window gets cancel and the second gets down
4286 firstWindow->consumeMotionCancel();
4287 secondWindow->consumeMotionDown();
4288 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4289 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4290
4291 // Send up event to the second window
4292 NotifyMotionArgs upMotionArgs =
4293 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4294 ADISPLAY_ID_DEFAULT);
4295 mDispatcher->notifyMotion(&upMotionArgs);
4296 // The first window gets no events and the second gets up
4297 firstWindow->assertNoEvents();
4298 secondWindow->consumeMotionUp();
4299 wallpaper1->assertNoEvents();
4300 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4301}
4302
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004303// For the cases of single pointer touch and two pointers non-split touch, the api's
4304// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4305// for the case where there are multiple pointers split across several windows.
4306INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4307 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004308 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4309 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004310 return dispatcher->transferTouch(destChannelToken,
4311 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004312 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004313 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4314 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004315 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004316 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004317 }));
4318
Svet Ganov5d3bc372020-01-26 23:11:07 -08004319TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004320 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004321
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004322 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004323 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4324 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004325 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004326
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004327 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004328 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4329 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004330 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004331
4332 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004334
4335 PointF pointInFirst = {300, 200};
4336 PointF pointInSecond = {300, 600};
4337
4338 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004339 NotifyMotionArgs firstDownMotionArgs =
4340 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4341 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004342 mDispatcher->notifyMotion(&firstDownMotionArgs);
4343 // Only the first window should get the down event
4344 firstWindow->consumeMotionDown();
4345 secondWindow->assertNoEvents();
4346
4347 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004348 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004349 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004350 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004351 mDispatcher->notifyMotion(&secondDownMotionArgs);
4352 // The first window gets a move and the second a down
4353 firstWindow->consumeMotionMove();
4354 secondWindow->consumeMotionDown();
4355
4356 // Transfer touch focus to the second window
4357 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4358 // The first window gets cancel and the new gets pointer down (it already saw down)
4359 firstWindow->consumeMotionCancel();
4360 secondWindow->consumeMotionPointerDown(1);
4361
4362 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004363 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004364 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004365 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004366 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4367 // The first window gets nothing and the second gets pointer up
4368 firstWindow->assertNoEvents();
4369 secondWindow->consumeMotionPointerUp(1);
4370
4371 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004372 NotifyMotionArgs upMotionArgs =
4373 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4374 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004375 mDispatcher->notifyMotion(&upMotionArgs);
4376 // The first window gets nothing and the second gets up
4377 firstWindow->assertNoEvents();
4378 secondWindow->consumeMotionUp();
4379}
4380
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004381// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4382// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4383// touch is not supported, so the touch should continue on those windows and the transferred-to
4384// window should get nothing.
4385TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4386 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4387
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004388 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004389 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4390 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004391 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004392
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004393 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004394 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4395 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004396 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004397
4398 // Add the windows to the dispatcher
4399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4400
4401 PointF pointInFirst = {300, 200};
4402 PointF pointInSecond = {300, 600};
4403
4404 // Send down to the first window
4405 NotifyMotionArgs firstDownMotionArgs =
4406 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4407 ADISPLAY_ID_DEFAULT, {pointInFirst});
4408 mDispatcher->notifyMotion(&firstDownMotionArgs);
4409 // Only the first window should get the down event
4410 firstWindow->consumeMotionDown();
4411 secondWindow->assertNoEvents();
4412
4413 // Send down to the second window
4414 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004415 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004416 {pointInFirst, pointInSecond});
4417 mDispatcher->notifyMotion(&secondDownMotionArgs);
4418 // The first window gets a move and the second a down
4419 firstWindow->consumeMotionMove();
4420 secondWindow->consumeMotionDown();
4421
4422 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004423 const bool transferred =
4424 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004425 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4426 ASSERT_FALSE(transferred);
4427 firstWindow->assertNoEvents();
4428 secondWindow->assertNoEvents();
4429
4430 // The rest of the dispatch should proceed as normal
4431 // Send pointer up to the second window
4432 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004433 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004434 {pointInFirst, pointInSecond});
4435 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4436 // The first window gets MOVE and the second gets pointer up
4437 firstWindow->consumeMotionMove();
4438 secondWindow->consumeMotionUp();
4439
4440 // Send up event to the first window
4441 NotifyMotionArgs upMotionArgs =
4442 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4443 ADISPLAY_ID_DEFAULT);
4444 mDispatcher->notifyMotion(&upMotionArgs);
4445 // The first window gets nothing and the second gets up
4446 firstWindow->consumeMotionUp();
4447 secondWindow->assertNoEvents();
4448}
4449
Arthur Hungabbb9d82021-09-01 14:52:30 +00004450// This case will create two windows and one mirrored window on the default display and mirror
4451// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4452// the windows info of second display before default display.
4453TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4454 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4455 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004456 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004457 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004458 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004459 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004460 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004461
4462 sp<FakeWindowHandle> mirrorWindowInPrimary =
4463 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4464 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004465
4466 sp<FakeWindowHandle> firstWindowInSecondary =
4467 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4468 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004469
4470 sp<FakeWindowHandle> secondWindowInSecondary =
4471 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4472 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004473
4474 // Update window info, let it find window handle of second display first.
4475 mDispatcher->setInputWindows(
4476 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4477 {ADISPLAY_ID_DEFAULT,
4478 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4479
4480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4481 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4482 {50, 50}))
4483 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4484
4485 // Window should receive motion event.
4486 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4487
4488 // Transfer touch focus
4489 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4490 secondWindowInPrimary->getToken()));
4491 // The first window gets cancel.
4492 firstWindowInPrimary->consumeMotionCancel();
4493 secondWindowInPrimary->consumeMotionDown();
4494
4495 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4496 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4497 ADISPLAY_ID_DEFAULT, {150, 50}))
4498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4499 firstWindowInPrimary->assertNoEvents();
4500 secondWindowInPrimary->consumeMotionMove();
4501
4502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4503 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4504 {150, 50}))
4505 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4506 firstWindowInPrimary->assertNoEvents();
4507 secondWindowInPrimary->consumeMotionUp();
4508}
4509
4510// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4511// 'transferTouch' api.
4512TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4514 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004515 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004516 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004517 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004518 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004519 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004520
4521 sp<FakeWindowHandle> mirrorWindowInPrimary =
4522 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4523 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004524
4525 sp<FakeWindowHandle> firstWindowInSecondary =
4526 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4527 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004528
4529 sp<FakeWindowHandle> secondWindowInSecondary =
4530 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4531 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004532
4533 // Update window info, let it find window handle of second display first.
4534 mDispatcher->setInputWindows(
4535 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4536 {ADISPLAY_ID_DEFAULT,
4537 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4538
4539 // Touch on second display.
4540 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4541 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4542 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4543
4544 // Window should receive motion event.
4545 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4546
4547 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004548 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004549
4550 // The first window gets cancel.
4551 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4552 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4553
4554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4555 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4556 SECOND_DISPLAY_ID, {150, 50}))
4557 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4558 firstWindowInPrimary->assertNoEvents();
4559 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4560
4561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4562 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4564 firstWindowInPrimary->assertNoEvents();
4565 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4566}
4567
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004568TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004570 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4571 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004572
Vishnu Nair47074b82020-08-14 11:54:47 -07004573 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004575 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004576
4577 window->consumeFocusEvent(true);
4578
4579 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4580 mDispatcher->notifyKey(&keyArgs);
4581
4582 // Window should receive key down event.
4583 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4584}
4585
4586TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004588 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4589 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004590
Arthur Hung72d8dc32020-03-28 00:48:39 +00004591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004592
4593 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4594 mDispatcher->notifyKey(&keyArgs);
4595 mDispatcher->waitForIdle();
4596
4597 window->assertNoEvents();
4598}
4599
4600// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4601TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004603 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4604 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004605
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004607
4608 // Send key
4609 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4610 mDispatcher->notifyKey(&keyArgs);
4611 // Send motion
4612 NotifyMotionArgs motionArgs =
4613 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4614 ADISPLAY_ID_DEFAULT);
4615 mDispatcher->notifyMotion(&motionArgs);
4616
4617 // Window should receive only the motion event
4618 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4619 window->assertNoEvents(); // Key event or focus event will not be received
4620}
4621
arthurhungea3f4fc2020-12-21 23:18:53 +08004622TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4624
arthurhungea3f4fc2020-12-21 23:18:53 +08004625 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004626 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4627 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004628 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004629
arthurhungea3f4fc2020-12-21 23:18:53 +08004630 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004631 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4632 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004633 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004634
4635 // Add the windows to the dispatcher
4636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4637
4638 PointF pointInFirst = {300, 200};
4639 PointF pointInSecond = {300, 600};
4640
4641 // Send down to the first window
4642 NotifyMotionArgs firstDownMotionArgs =
4643 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4644 ADISPLAY_ID_DEFAULT, {pointInFirst});
4645 mDispatcher->notifyMotion(&firstDownMotionArgs);
4646 // Only the first window should get the down event
4647 firstWindow->consumeMotionDown();
4648 secondWindow->assertNoEvents();
4649
4650 // Send down to the second window
4651 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004652 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004653 {pointInFirst, pointInSecond});
4654 mDispatcher->notifyMotion(&secondDownMotionArgs);
4655 // The first window gets a move and the second a down
4656 firstWindow->consumeMotionMove();
4657 secondWindow->consumeMotionDown();
4658
4659 // Send pointer cancel to the second window
4660 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004661 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004662 {pointInFirst, pointInSecond});
4663 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4664 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4665 // The first window gets move and the second gets cancel.
4666 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4667 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4668
4669 // Send up event.
4670 NotifyMotionArgs upMotionArgs =
4671 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4672 ADISPLAY_ID_DEFAULT);
4673 mDispatcher->notifyMotion(&upMotionArgs);
4674 // The first window gets up and the second gets nothing.
4675 firstWindow->consumeMotionUp();
4676 secondWindow->assertNoEvents();
4677}
4678
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004679TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4681
4682 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004683 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4685 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4686 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4687 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4688
Harry Cutts33476232023-01-30 19:57:29 +00004689 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004690 window->assertNoEvents();
4691 mDispatcher->waitForIdle();
4692}
4693
chaviwd1c23182019-12-20 18:44:56 -08004694class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004695public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004696 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004697 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004698 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004699 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004700 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004701 }
4702
chaviwd1c23182019-12-20 18:44:56 -08004703 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4704
4705 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4706 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4707 expectedDisplayId, expectedFlags);
4708 }
4709
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4711
4712 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4713
chaviwd1c23182019-12-20 18:44:56 -08004714 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4715 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4716 expectedDisplayId, expectedFlags);
4717 }
4718
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004719 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4720 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4721 expectedDisplayId, expectedFlags);
4722 }
4723
chaviwd1c23182019-12-20 18:44:56 -08004724 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4725 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4726 expectedDisplayId, expectedFlags);
4727 }
4728
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004729 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004730 mInputReceiver->consumeMotionEvent(
4731 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4732 WithDisplayId(expectedDisplayId),
4733 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004734 }
4735
Arthur Hungfbfa5722021-11-16 02:45:54 +00004736 void consumeMotionPointerDown(int32_t pointerIdx) {
4737 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4738 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4739 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004740 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004741 }
4742
Evan Rosky84f07f02021-04-16 10:42:42 -07004743 MotionEvent* consumeMotion() {
4744 InputEvent* event = mInputReceiver->consume();
4745 if (!event) {
4746 ADD_FAILURE() << "No event was produced";
4747 return nullptr;
4748 }
4749 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4750 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4751 return nullptr;
4752 }
4753 return static_cast<MotionEvent*>(event);
4754 }
4755
chaviwd1c23182019-12-20 18:44:56 -08004756 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4757
4758private:
4759 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004760};
4761
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004762using InputDispatcherMonitorTest = InputDispatcherTest;
4763
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004764/**
4765 * Two entities that receive touch: A window, and a global monitor.
4766 * The touch goes to the window, and then the window disappears.
4767 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4768 * for the monitor, as well.
4769 * 1. foregroundWindow
4770 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4771 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004772TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004773 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4774 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004775 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004776
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004777 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004778
4779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4782 {100, 200}))
4783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4784
4785 // Both the foreground window and the global monitor should receive the touch down
4786 window->consumeMotionDown();
4787 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4788
4789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4790 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4791 ADISPLAY_ID_DEFAULT, {110, 200}))
4792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4793
4794 window->consumeMotionMove();
4795 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4796
4797 // Now the foreground window goes away
4798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4799 window->consumeMotionCancel();
4800 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4801
4802 // If more events come in, there will be no more foreground window to send them to. This will
4803 // cause a cancel for the monitor, as well.
4804 ASSERT_EQ(InputEventInjectionResult::FAILED,
4805 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4806 ADISPLAY_ID_DEFAULT, {120, 200}))
4807 << "Injection should fail because the window was removed";
4808 window->assertNoEvents();
4809 // Global monitor now gets the cancel
4810 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4811}
4812
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004813TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004815 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4816 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004818
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004819 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004820
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004824 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004825 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004826}
4827
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004828TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4829 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004830
Chris Yea209fde2020-07-22 13:54:51 -07004831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004832 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4833 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004835
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004839 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004840 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004841
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004842 // Pilfer pointers from the monitor.
4843 // This should not do anything and the window should continue to receive events.
4844 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004845
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004847 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4848 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004850
4851 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4852 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004853}
4854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004856 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004857 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4858 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4860 window->setWindowOffset(20, 40);
4861 window->setWindowTransform(0, 1, -1, 0);
4862
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004863 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004864
4865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4866 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4868 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4869 MotionEvent* event = monitor.consumeMotion();
4870 // Even though window has transform, gesture monitor must not.
4871 ASSERT_EQ(ui::Transform(), event->getTransform());
4872}
4873
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004874TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004875 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004876 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004877
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004878 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004879 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004880 << "Injection should fail if there is a monitor, but no touchable window";
4881 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004882}
4883
chaviw81e2bb92019-12-18 15:03:51 -08004884TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004885 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004886 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4887 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004888
Arthur Hung72d8dc32020-03-28 00:48:39 +00004889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004890
4891 NotifyMotionArgs motionArgs =
4892 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4893 ADISPLAY_ID_DEFAULT);
4894
4895 mDispatcher->notifyMotion(&motionArgs);
4896 // Window should receive motion down event.
4897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4898
4899 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004900 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004901 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4902 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4903 motionArgs.pointerCoords[0].getX() - 10);
4904
4905 mDispatcher->notifyMotion(&motionArgs);
4906 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004907 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004908}
4909
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004910/**
4911 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4912 * the device default right away. In the test scenario, we check both the default value,
4913 * and the action of enabling / disabling.
4914 */
4915TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004917 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4918 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004919 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004920
4921 // Set focused application.
4922 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004923 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004924
4925 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004927 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004928 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004929
4930 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004931 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004933 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004934
4935 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004936 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004937 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004938 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004939 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004941 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004942 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004943
4944 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004945 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004947 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004948
4949 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004950 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004951 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004952 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004953 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004955 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004956 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004957
4958 window->assertNoEvents();
4959}
4960
Gang Wange9087892020-01-07 12:17:14 -05004961TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004962 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004963 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4964 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004965
4966 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004967 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004968
Arthur Hung72d8dc32020-03-28 00:48:39 +00004969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004970 setFocusedWindow(window);
4971
Harry Cutts33476232023-01-30 19:57:29 +00004972 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004973
4974 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4975 mDispatcher->notifyKey(&keyArgs);
4976
4977 InputEvent* event = window->consume();
4978 ASSERT_NE(event, nullptr);
4979
4980 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4981 ASSERT_NE(verified, nullptr);
4982 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4983
4984 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4985 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4986 ASSERT_EQ(keyArgs.source, verified->source);
4987 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4988
4989 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4990
4991 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004992 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004993 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004994 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4995 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4996 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4997 ASSERT_EQ(0, verifiedKey.repeatCount);
4998}
4999
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005000TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005001 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005002 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5003 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005004
5005 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5006
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005007 ui::Transform transform;
5008 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5009
5010 gui::DisplayInfo displayInfo;
5011 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
5012 displayInfo.transform = transform;
5013
5014 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005015
5016 NotifyMotionArgs motionArgs =
5017 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5018 ADISPLAY_ID_DEFAULT);
5019 mDispatcher->notifyMotion(&motionArgs);
5020
5021 InputEvent* event = window->consume();
5022 ASSERT_NE(event, nullptr);
5023
5024 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5025 ASSERT_NE(verified, nullptr);
5026 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
5027
5028 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
5029 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
5030 EXPECT_EQ(motionArgs.source, verified->source);
5031 EXPECT_EQ(motionArgs.displayId, verified->displayId);
5032
5033 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
5034
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005035 const vec2 rawXY =
5036 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
5037 motionArgs.pointerCoords[0].getXYValue());
5038 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
5039 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005040 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005041 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005042 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005043 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
5044 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
5045}
5046
chaviw09c8d2d2020-08-24 15:48:26 -07005047/**
5048 * Ensure that separate calls to sign the same data are generating the same key.
5049 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
5050 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
5051 * tests.
5052 */
5053TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
5054 KeyEvent event = getTestKeyEvent();
5055 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5056
5057 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
5058 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
5059 ASSERT_EQ(hmac1, hmac2);
5060}
5061
5062/**
5063 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
5064 */
5065TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
5066 KeyEvent event = getTestKeyEvent();
5067 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5068 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
5069
5070 verifiedEvent.deviceId += 1;
5071 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5072
5073 verifiedEvent.source += 1;
5074 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5075
5076 verifiedEvent.eventTimeNanos += 1;
5077 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5078
5079 verifiedEvent.displayId += 1;
5080 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5081
5082 verifiedEvent.action += 1;
5083 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5084
5085 verifiedEvent.downTimeNanos += 1;
5086 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5087
5088 verifiedEvent.flags += 1;
5089 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5090
5091 verifiedEvent.keyCode += 1;
5092 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5093
5094 verifiedEvent.scanCode += 1;
5095 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5096
5097 verifiedEvent.metaState += 1;
5098 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5099
5100 verifiedEvent.repeatCount += 1;
5101 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5102}
5103
Vishnu Nair958da932020-08-21 17:12:37 -07005104TEST_F(InputDispatcherTest, SetFocusedWindow) {
5105 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5106 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005107 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005108 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005109 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005110 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5111
5112 // Top window is also focusable but is not granted focus.
5113 windowTop->setFocusable(true);
5114 windowSecond->setFocusable(true);
5115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5116 setFocusedWindow(windowSecond);
5117
5118 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5120 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005121
5122 // Focused window should receive event.
5123 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5124 windowTop->assertNoEvents();
5125}
5126
5127TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5128 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5129 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005130 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5132
5133 window->setFocusable(true);
5134 // Release channel for window is no longer valid.
5135 window->releaseChannel();
5136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5137 setFocusedWindow(window);
5138
5139 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5141 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005142
5143 // window channel is invalid, so it should not receive any input event.
5144 window->assertNoEvents();
5145}
5146
5147TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5149 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005150 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005151 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5153
Vishnu Nair958da932020-08-21 17:12:37 -07005154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5155 setFocusedWindow(window);
5156
5157 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005158 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5159 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005160
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005161 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005162 window->assertNoEvents();
5163}
5164
5165TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5166 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5167 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005168 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005169 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005170 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005171 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5172
5173 windowTop->setFocusable(true);
5174 windowSecond->setFocusable(true);
5175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5176 setFocusedWindow(windowTop);
5177 windowTop->consumeFocusEvent(true);
5178
5179 setFocusedWindow(windowSecond, windowTop);
5180 windowSecond->consumeFocusEvent(true);
5181 windowTop->consumeFocusEvent(false);
5182
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5184 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005185
5186 // Focused window should receive event.
5187 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5188}
5189
5190TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5191 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5192 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005193 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005194 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005195 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005196 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5197
5198 windowTop->setFocusable(true);
5199 windowSecond->setFocusable(true);
5200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5201 setFocusedWindow(windowSecond, windowTop);
5202
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005203 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5204 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005205
5206 // Event should be dropped.
5207 windowTop->assertNoEvents();
5208 windowSecond->assertNoEvents();
5209}
5210
5211TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5213 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005214 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005215 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005216 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5217 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005218 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5219
5220 window->setFocusable(true);
5221 previousFocusedWindow->setFocusable(true);
5222 window->setVisible(false);
5223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5224 setFocusedWindow(previousFocusedWindow);
5225 previousFocusedWindow->consumeFocusEvent(true);
5226
5227 // Requesting focus on invisible window takes focus from currently focused window.
5228 setFocusedWindow(window);
5229 previousFocusedWindow->consumeFocusEvent(false);
5230
5231 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005233 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5234 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005235
5236 // Window does not get focus event or key down.
5237 window->assertNoEvents();
5238
5239 // Window becomes visible.
5240 window->setVisible(true);
5241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5242
5243 // Window receives focus event.
5244 window->consumeFocusEvent(true);
5245 // Focused window receives key down.
5246 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5247}
5248
Vishnu Nair599f1412021-06-21 10:39:58 -07005249TEST_F(InputDispatcherTest, DisplayRemoved) {
5250 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5251 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005252 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5254
5255 // window is granted focus.
5256 window->setFocusable(true);
5257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5258 setFocusedWindow(window);
5259 window->consumeFocusEvent(true);
5260
5261 // When a display is removed window loses focus.
5262 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5263 window->consumeFocusEvent(false);
5264}
5265
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005266/**
5267 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5268 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5269 * of the 'slipperyEnterWindow'.
5270 *
5271 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5272 * a way so that the touched location is no longer covered by the top window.
5273 *
5274 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5275 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5276 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5277 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5278 * with ACTION_DOWN).
5279 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5280 * window moved itself away from the touched location and had Flag::SLIPPERY.
5281 *
5282 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5283 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5284 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5285 *
5286 * In this test, we ensure that the event received by the bottom window has
5287 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5288 */
5289TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005290 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5291 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005292
5293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5294 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5295
5296 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005297 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005298 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005299 // Make sure this one overlaps the bottom window
5300 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5301 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5302 // one. Windows with the same owner are not considered to be occluding each other.
5303 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5304
5305 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005306 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005307 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5308
5309 mDispatcher->setInputWindows(
5310 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5311
5312 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5313 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5314 ADISPLAY_ID_DEFAULT, {{50, 50}});
5315 mDispatcher->notifyMotion(&args);
5316 slipperyExitWindow->consumeMotionDown();
5317 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5318 mDispatcher->setInputWindows(
5319 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5320
5321 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5322 ADISPLAY_ID_DEFAULT, {{51, 51}});
5323 mDispatcher->notifyMotion(&args);
5324
5325 slipperyExitWindow->consumeMotionCancel();
5326
5327 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5328 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5329}
5330
Garfield Tan1c7bc862020-01-28 13:24:04 -08005331class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5332protected:
5333 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5334 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5335
Chris Yea209fde2020-07-22 13:54:51 -07005336 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005337 sp<FakeWindowHandle> mWindow;
5338
5339 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005340 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005341 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005342 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005343 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5344 ASSERT_EQ(OK, mDispatcher->start());
5345
5346 setUpWindow();
5347 }
5348
5349 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005350 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005351 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005352
Vishnu Nair47074b82020-08-14 11:54:47 -07005353 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005355 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005356 mWindow->consumeFocusEvent(true);
5357 }
5358
Chris Ye2ad95392020-09-01 13:44:44 -07005359 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005360 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005361 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005362 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5363 mDispatcher->notifyKey(&keyArgs);
5364
5365 // Window should receive key down event.
5366 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5367 }
5368
5369 void expectKeyRepeatOnce(int32_t repeatCount) {
5370 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5371 InputEvent* repeatEvent = mWindow->consume();
5372 ASSERT_NE(nullptr, repeatEvent);
5373
5374 uint32_t eventType = repeatEvent->getType();
5375 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5376
5377 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5378 uint32_t eventAction = repeatKeyEvent->getAction();
5379 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5380 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5381 }
5382
Chris Ye2ad95392020-09-01 13:44:44 -07005383 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005384 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005385 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005386 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5387 mDispatcher->notifyKey(&keyArgs);
5388
5389 // Window should receive key down event.
5390 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005391 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005392 }
5393};
5394
5395TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005396 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005397 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5398 expectKeyRepeatOnce(repeatCount);
5399 }
5400}
5401
5402TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005403 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005404 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5405 expectKeyRepeatOnce(repeatCount);
5406 }
Harry Cutts33476232023-01-30 19:57:29 +00005407 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005408 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005409 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5410 expectKeyRepeatOnce(repeatCount);
5411 }
5412}
5413
5414TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005415 sendAndConsumeKeyDown(/*deviceId=*/1);
5416 expectKeyRepeatOnce(/*repeatCount=*/1);
5417 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005418 mWindow->assertNoEvents();
5419}
5420
5421TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005422 sendAndConsumeKeyDown(/*deviceId=*/1);
5423 expectKeyRepeatOnce(/*repeatCount=*/1);
5424 sendAndConsumeKeyDown(/*deviceId=*/2);
5425 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005426 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005427 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005428 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005429 expectKeyRepeatOnce(/*repeatCount=*/2);
5430 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005431 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005432 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005433 mWindow->assertNoEvents();
5434}
5435
5436TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005437 sendAndConsumeKeyDown(/*deviceId=*/1);
5438 expectKeyRepeatOnce(/*repeatCount=*/1);
5439 sendAndConsumeKeyDown(/*deviceId=*/2);
5440 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005441 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005442 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005443 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005444 mWindow->assertNoEvents();
5445}
5446
liushenxiang42232912021-05-21 20:24:09 +08005447TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5448 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005449 expectKeyRepeatOnce(/*repeatCount=*/1);
5450 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005451 mDispatcher->notifyDeviceReset(&args);
5452 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5453 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5454 mWindow->assertNoEvents();
5455}
5456
Garfield Tan1c7bc862020-01-28 13:24:04 -08005457TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005458 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005459 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005460 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5461 InputEvent* repeatEvent = mWindow->consume();
5462 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5463 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5464 IdGenerator::getSource(repeatEvent->getId()));
5465 }
5466}
5467
5468TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005469 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005470 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005471
5472 std::unordered_set<int32_t> idSet;
5473 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5474 InputEvent* repeatEvent = mWindow->consume();
5475 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5476 int32_t id = repeatEvent->getId();
5477 EXPECT_EQ(idSet.end(), idSet.find(id));
5478 idSet.insert(id);
5479 }
5480}
5481
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005482/* Test InputDispatcher for MultiDisplay */
5483class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5484public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005485 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005486 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005487
Chris Yea209fde2020-07-22 13:54:51 -07005488 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005489 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005490 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005491
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005492 // Set focus window for primary display, but focused display would be second one.
5493 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005494 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005496 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005497 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005498
Chris Yea209fde2020-07-22 13:54:51 -07005499 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005500 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005501 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005502 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005503 // Set focus display to second one.
5504 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5505 // Set focus window for second display.
5506 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005507 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005508 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005509 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005510 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005511 }
5512
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005513 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005514 InputDispatcherTest::TearDown();
5515
Chris Yea209fde2020-07-22 13:54:51 -07005516 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005517 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005518 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005519 windowInSecondary.clear();
5520 }
5521
5522protected:
Chris Yea209fde2020-07-22 13:54:51 -07005523 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005524 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005525 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005526 sp<FakeWindowHandle> windowInSecondary;
5527};
5528
5529TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5530 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5532 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5533 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005534 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005535 windowInSecondary->assertNoEvents();
5536
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005537 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005541 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005542 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005543}
5544
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005545TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005546 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5548 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005549 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005550 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005551 windowInSecondary->assertNoEvents();
5552
5553 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005555 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005556 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005557 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005558
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005559 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005560 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005561
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005562 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005563 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5564 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005565
5566 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005567 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005568 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005569 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005570 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005571 windowInSecondary->assertNoEvents();
5572}
5573
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005574// Test per-display input monitors for motion event.
5575TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005576 FakeMonitorReceiver monitorInPrimary =
5577 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5578 FakeMonitorReceiver monitorInSecondary =
5579 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005580
5581 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005585 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005586 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005587 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005588 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005589
5590 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005594 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005595 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005596 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005597 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005598
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08005599 // Lift up the touch from the second display
5600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5601 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5603 windowInSecondary->consumeMotionUp(SECOND_DISPLAY_ID);
5604 monitorInSecondary.consumeMotionUp(SECOND_DISPLAY_ID);
5605
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005606 // Test inject a non-pointer motion event.
5607 // If specific a display, it will dispatch to the focused window of particular display,
5608 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5610 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005612 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005613 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005614 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005615 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005616}
5617
5618// Test per-display input monitors for key event.
5619TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005620 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005621 FakeMonitorReceiver monitorInPrimary =
5622 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5623 FakeMonitorReceiver monitorInSecondary =
5624 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005625
5626 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5628 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005629 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005630 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005631 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005632 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005633}
5634
Vishnu Nair958da932020-08-21 17:12:37 -07005635TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5636 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005637 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005638 secondWindowInPrimary->setFocusable(true);
5639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5640 setFocusedWindow(secondWindowInPrimary);
5641 windowInPrimary->consumeFocusEvent(false);
5642 secondWindowInPrimary->consumeFocusEvent(true);
5643
5644 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005645 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5646 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005647 windowInPrimary->assertNoEvents();
5648 windowInSecondary->assertNoEvents();
5649 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5650}
5651
Arthur Hungdfd528e2021-12-08 13:23:04 +00005652TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5653 FakeMonitorReceiver monitorInPrimary =
5654 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5655 FakeMonitorReceiver monitorInSecondary =
5656 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5657
5658 // Test touch down on primary display.
5659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5662 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5663 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5664
5665 // Test touch down on second display.
5666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5668 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5669 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5670 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5671
5672 // Trigger cancel touch.
5673 mDispatcher->cancelCurrentTouch();
5674 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5675 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5676 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5677 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5678
5679 // Test inject a move motion event, no window/monitor should receive the event.
5680 ASSERT_EQ(InputEventInjectionResult::FAILED,
5681 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5682 ADISPLAY_ID_DEFAULT, {110, 200}))
5683 << "Inject motion event should return InputEventInjectionResult::FAILED";
5684 windowInPrimary->assertNoEvents();
5685 monitorInPrimary.assertNoEvents();
5686
5687 ASSERT_EQ(InputEventInjectionResult::FAILED,
5688 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5689 SECOND_DISPLAY_ID, {110, 200}))
5690 << "Inject motion event should return InputEventInjectionResult::FAILED";
5691 windowInSecondary->assertNoEvents();
5692 monitorInSecondary.assertNoEvents();
5693}
5694
Jackal Guof9696682018-10-05 12:23:23 +08005695class InputFilterTest : public InputDispatcherTest {
5696protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005697 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5698 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005699 NotifyMotionArgs motionArgs;
5700
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005701 motionArgs =
5702 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005703 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005704 motionArgs =
5705 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005706 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005707 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005708 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005709 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5710 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005711 } else {
5712 mFakePolicy->assertFilterInputEventWasNotCalled();
5713 }
5714 }
5715
5716 void testNotifyKey(bool expectToBeFiltered) {
5717 NotifyKeyArgs keyArgs;
5718
5719 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5720 mDispatcher->notifyKey(&keyArgs);
5721 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5722 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005723 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005724
5725 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005726 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005727 } else {
5728 mFakePolicy->assertFilterInputEventWasNotCalled();
5729 }
5730 }
5731};
5732
5733// Test InputFilter for MotionEvent
5734TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5735 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5736 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5737 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5738
5739 // Enable InputFilter
5740 mDispatcher->setInputFilterEnabled(true);
5741 // Test touch on both primary and second display, and check if both events are filtered.
5742 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5743 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5744
5745 // Disable InputFilter
5746 mDispatcher->setInputFilterEnabled(false);
5747 // Test touch on both primary and second display, and check if both events aren't filtered.
5748 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5749 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5750}
5751
5752// Test InputFilter for KeyEvent
5753TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5754 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5755 testNotifyKey(/*expectToBeFiltered*/ false);
5756
5757 // Enable InputFilter
5758 mDispatcher->setInputFilterEnabled(true);
5759 // Send a key event, and check if it is filtered.
5760 testNotifyKey(/*expectToBeFiltered*/ true);
5761
5762 // Disable InputFilter
5763 mDispatcher->setInputFilterEnabled(false);
5764 // Send a key event, and check if it isn't filtered.
5765 testNotifyKey(/*expectToBeFiltered*/ false);
5766}
5767
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005768// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5769// logical display coordinate space.
5770TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5771 ui::Transform firstDisplayTransform;
5772 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5773 ui::Transform secondDisplayTransform;
5774 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5775
5776 std::vector<gui::DisplayInfo> displayInfos(2);
5777 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5778 displayInfos[0].transform = firstDisplayTransform;
5779 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5780 displayInfos[1].transform = secondDisplayTransform;
5781
5782 mDispatcher->onWindowInfosChanged({}, displayInfos);
5783
5784 // Enable InputFilter
5785 mDispatcher->setInputFilterEnabled(true);
5786
5787 // Ensure the correct transforms are used for the displays.
5788 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5789 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5790}
5791
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005792class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5793protected:
5794 virtual void SetUp() override {
5795 InputDispatcherTest::SetUp();
5796
5797 /**
5798 * We don't need to enable input filter to test the injected event policy, but we enabled it
5799 * here to make the tests more realistic, since this policy only matters when inputfilter is
5800 * on.
5801 */
5802 mDispatcher->setInputFilterEnabled(true);
5803
5804 std::shared_ptr<InputApplicationHandle> application =
5805 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005806 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5807 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005808
5809 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5810 mWindow->setFocusable(true);
5811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5812 setFocusedWindow(mWindow);
5813 mWindow->consumeFocusEvent(true);
5814 }
5815
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005816 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5817 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005818 KeyEvent event;
5819
5820 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5821 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5822 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005823 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005824 const int32_t additionalPolicyFlags =
5825 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005827 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005828 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5829 policyFlags | additionalPolicyFlags));
5830
5831 InputEvent* received = mWindow->consume();
5832 ASSERT_NE(nullptr, received);
5833 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005834 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5835 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5836 ASSERT_EQ(flags, keyEvent.getFlags());
5837 }
5838
5839 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5840 int32_t flags) {
5841 MotionEvent event;
5842 PointerProperties pointerProperties[1];
5843 PointerCoords pointerCoords[1];
5844 pointerProperties[0].clear();
5845 pointerProperties[0].id = 0;
5846 pointerCoords[0].clear();
5847 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5848 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5849
5850 ui::Transform identityTransform;
5851 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5852 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5853 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5854 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5855 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005856 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005857 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005858 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5859
5860 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005862 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005863 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5864 policyFlags | additionalPolicyFlags));
5865
5866 InputEvent* received = mWindow->consume();
5867 ASSERT_NE(nullptr, received);
5868 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5869 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5870 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5871 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005872 }
5873
5874private:
5875 sp<FakeWindowHandle> mWindow;
5876};
5877
5878TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005879 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5880 // filter. Without it, the event will no different from a regularly injected event, and the
5881 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005882 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5883 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005884}
5885
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005886TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005887 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005888 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005889 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5890}
5891
5892TEST_F(InputFilterInjectionPolicyTest,
5893 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5894 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005895 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005896 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005897}
5898
5899TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005900 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5901 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005902}
5903
chaviwfd6d3512019-03-25 13:23:49 -07005904class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005905 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005906 InputDispatcherTest::SetUp();
5907
Chris Yea209fde2020-07-22 13:54:51 -07005908 std::shared_ptr<FakeApplicationHandle> application =
5909 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005910 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005911 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005912 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005913
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005914 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005915 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005916 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005917
5918 // Set focused application.
5919 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005920 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005921
5922 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005924 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005925 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005926 }
5927
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005928 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005929 InputDispatcherTest::TearDown();
5930
5931 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005932 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005933 }
5934
5935protected:
5936 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005937 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005938 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005939};
5940
5941// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5942// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5943// the onPointerDownOutsideFocus callback.
5944TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5947 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005949 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005950
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005951 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005952 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5953}
5954
5955// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5956// DOWN on the window that doesn't have focus. Ensure no window received the
5957// onPointerDownOutsideFocus callback.
5958TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005962 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005963
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005964 ASSERT_TRUE(mDispatcher->waitForIdle());
5965 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005966}
5967
5968// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5969// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5970TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5972 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005973 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005974 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005975
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005976 ASSERT_TRUE(mDispatcher->waitForIdle());
5977 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005978}
5979
5980// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5981// DOWN on the window that already has focus. Ensure no window received the
5982// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005983TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005985 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005986 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005988 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005989
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005990 ASSERT_TRUE(mDispatcher->waitForIdle());
5991 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005992}
5993
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005994// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5995// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5996TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5997 const MotionEvent event =
5998 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5999 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00006000 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08006001 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
6002 .build();
6003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
6004 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6005 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
6006
6007 ASSERT_TRUE(mDispatcher->waitForIdle());
6008 mFakePolicy->assertOnPointerDownWasNotCalled();
6009 // Ensure that the unfocused window did not receive any FOCUS events.
6010 mUnfocusedWindow->assertNoEvents();
6011}
6012
chaviwaf87b3e2019-10-01 16:59:28 -07006013// These tests ensures we can send touch events to a single client when there are multiple input
6014// windows that point to the same client token.
6015class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
6016 virtual void SetUp() override {
6017 InputDispatcherTest::SetUp();
6018
Chris Yea209fde2020-07-22 13:54:51 -07006019 std::shared_ptr<FakeApplicationHandle> application =
6020 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006021 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
6022 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07006023 mWindow1->setFrame(Rect(0, 0, 100, 100));
6024
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006025 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
6026 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07006027 mWindow2->setFrame(Rect(100, 100, 200, 200));
6028
Arthur Hung72d8dc32020-03-28 00:48:39 +00006029 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07006030 }
6031
6032protected:
6033 sp<FakeWindowHandle> mWindow1;
6034 sp<FakeWindowHandle> mWindow2;
6035
6036 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05006037 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07006038 vec2 vals = windowInfo->transform.transform(point.x, point.y);
6039 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07006040 }
6041
6042 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
6043 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01006044 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07006045 InputEvent* event = window->consume();
6046
6047 ASSERT_NE(nullptr, event) << name.c_str()
6048 << ": consumer should have returned non-NULL event.";
6049
6050 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
6051 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
6052 << " event, got " << inputEventTypeToString(event->getType()) << " event";
6053
6054 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00006055 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08006056 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07006057
6058 for (size_t i = 0; i < points.size(); i++) {
6059 float expectedX = points[i].x;
6060 float expectedY = points[i].y;
6061
6062 EXPECT_EQ(expectedX, motionEvent.getX(i))
6063 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
6064 << ", got " << motionEvent.getX(i);
6065 EXPECT_EQ(expectedY, motionEvent.getY(i))
6066 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
6067 << ", got " << motionEvent.getY(i);
6068 }
6069 }
chaviw9eaa22c2020-07-01 16:21:27 -07006070
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08006071 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07006072 std::vector<PointF> expectedPoints) {
6073 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
6074 ADISPLAY_ID_DEFAULT, touchedPoints);
6075 mDispatcher->notifyMotion(&motionArgs);
6076
6077 // Always consume from window1 since it's the window that has the InputReceiver
6078 consumeMotionEvent(mWindow1, action, expectedPoints);
6079 }
chaviwaf87b3e2019-10-01 16:59:28 -07006080};
6081
6082TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
6083 // Touch Window 1
6084 PointF touchedPoint = {10, 10};
6085 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006086 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006087
6088 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006089 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006090
6091 // Touch Window 2
6092 touchedPoint = {150, 150};
6093 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006094 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006095}
6096
chaviw9eaa22c2020-07-01 16:21:27 -07006097TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
6098 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07006099 mWindow2->setWindowScale(0.5f, 0.5f);
6100
6101 // Touch Window 1
6102 PointF touchedPoint = {10, 10};
6103 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006104 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006105 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006106 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006107
6108 // Touch Window 2
6109 touchedPoint = {150, 150};
6110 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006111 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
6112 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006113
chaviw9eaa22c2020-07-01 16:21:27 -07006114 // Update the transform so rotation is set
6115 mWindow2->setWindowTransform(0, -1, 1, 0);
6116 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
6117 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006118}
6119
chaviw9eaa22c2020-07-01 16:21:27 -07006120TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006121 mWindow2->setWindowScale(0.5f, 0.5f);
6122
6123 // Touch Window 1
6124 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6125 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006126 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006127
6128 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006129 touchedPoints.push_back(PointF{150, 150});
6130 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006131 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006132
chaviw9eaa22c2020-07-01 16:21:27 -07006133 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006134 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006135 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006136
chaviw9eaa22c2020-07-01 16:21:27 -07006137 // Update the transform so rotation is set for Window 2
6138 mWindow2->setWindowTransform(0, -1, 1, 0);
6139 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006140 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006141}
6142
chaviw9eaa22c2020-07-01 16:21:27 -07006143TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006144 mWindow2->setWindowScale(0.5f, 0.5f);
6145
6146 // Touch Window 1
6147 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6148 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006149 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006150
6151 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006152 touchedPoints.push_back(PointF{150, 150});
6153 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006154
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006155 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006156
6157 // Move both windows
6158 touchedPoints = {{20, 20}, {175, 175}};
6159 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6160 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6161
chaviw9eaa22c2020-07-01 16:21:27 -07006162 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006163
chaviw9eaa22c2020-07-01 16:21:27 -07006164 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006165 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006166 expectedPoints.pop_back();
6167
6168 // Touch Window 2
6169 mWindow2->setWindowTransform(0, -1, 1, 0);
6170 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006171 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006172
6173 // Move both windows
6174 touchedPoints = {{20, 20}, {175, 175}};
6175 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6176 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6177
6178 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006179}
6180
6181TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6182 mWindow1->setWindowScale(0.5f, 0.5f);
6183
6184 // Touch Window 1
6185 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6186 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006187 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006188
6189 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006190 touchedPoints.push_back(PointF{150, 150});
6191 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006192
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006193 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006194
6195 // Move both windows
6196 touchedPoints = {{20, 20}, {175, 175}};
6197 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6198 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6199
chaviw9eaa22c2020-07-01 16:21:27 -07006200 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006201}
6202
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006203class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6204 virtual void SetUp() override {
6205 InputDispatcherTest::SetUp();
6206
Chris Yea209fde2020-07-22 13:54:51 -07006207 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006208 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006209 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6210 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006211 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006212 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006213 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006214
6215 // Set focused application.
6216 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6217
6218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006219 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006220 mWindow->consumeFocusEvent(true);
6221 }
6222
6223 virtual void TearDown() override {
6224 InputDispatcherTest::TearDown();
6225 mWindow.clear();
6226 }
6227
6228protected:
Chris Yea209fde2020-07-22 13:54:51 -07006229 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006230 sp<FakeWindowHandle> mWindow;
6231 static constexpr PointF WINDOW_LOCATION = {20, 20};
6232
6233 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006235 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6236 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006238 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6239 WINDOW_LOCATION));
6240 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006241
6242 sp<FakeWindowHandle> addSpyWindow() {
6243 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006244 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006245 spy->setTrustedOverlay(true);
6246 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006247 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006248 spy->setDispatchingTimeout(30ms);
6249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6250 return spy;
6251 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006252};
6253
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006254// Send a tap and respond, which should not cause an ANR.
6255TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6256 tapOnWindow();
6257 mWindow->consumeMotionDown();
6258 mWindow->consumeMotionUp();
6259 ASSERT_TRUE(mDispatcher->waitForIdle());
6260 mFakePolicy->assertNotifyAnrWasNotCalled();
6261}
6262
6263// Send a regular key and respond, which should not cause an ANR.
6264TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006266 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6267 ASSERT_TRUE(mDispatcher->waitForIdle());
6268 mFakePolicy->assertNotifyAnrWasNotCalled();
6269}
6270
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006271TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6272 mWindow->setFocusable(false);
6273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6274 mWindow->consumeFocusEvent(false);
6275
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006276 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006277 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6278 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6279 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006280 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006281 // Key will not go to window because we have no focused window.
6282 // The 'no focused window' ANR timer should start instead.
6283
6284 // Now, the focused application goes away.
6285 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6286 // The key should get dropped and there should be no ANR.
6287
6288 ASSERT_TRUE(mDispatcher->waitForIdle());
6289 mFakePolicy->assertNotifyAnrWasNotCalled();
6290}
6291
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006292// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006293// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6294// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006295TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006297 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6298 WINDOW_LOCATION));
6299
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006300 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6301 ASSERT_TRUE(sequenceNum);
6302 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006303 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006304
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006305 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006306 mWindow->consumeMotionEvent(
6307 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006308 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006309 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006310}
6311
6312// Send a key to the app and have the app not respond right away.
6313TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6314 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006316 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6317 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006318 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006319 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006320 ASSERT_TRUE(mDispatcher->waitForIdle());
6321}
6322
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323// We have a focused application, but no focused window
6324TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006325 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006326 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6327 mWindow->consumeFocusEvent(false);
6328
6329 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006331 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6332 WINDOW_LOCATION));
6333 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6334 mDispatcher->waitForIdle();
6335 mFakePolicy->assertNotifyAnrWasNotCalled();
6336
6337 // Once a focused event arrives, we get an ANR for this application
6338 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6339 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006340 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006341 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6342 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006343 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006344 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006345 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346 ASSERT_TRUE(mDispatcher->waitForIdle());
6347}
6348
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006349/**
6350 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6351 * there will not be an ANR.
6352 */
6353TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6354 mWindow->setFocusable(false);
6355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6356 mWindow->consumeFocusEvent(false);
6357
6358 KeyEvent event;
6359 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6360 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6361
6362 // Define a valid key down event that is stale (too old).
6363 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6364 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006365 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006366
6367 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6368
6369 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006370 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006371 InputEventInjectionSync::WAIT_FOR_RESULT,
6372 INJECT_EVENT_TIMEOUT, policyFlags);
6373 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6374 << "Injection should fail because the event is stale";
6375
6376 ASSERT_TRUE(mDispatcher->waitForIdle());
6377 mFakePolicy->assertNotifyAnrWasNotCalled();
6378 mWindow->assertNoEvents();
6379}
6380
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006381// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006382// Make sure that we don't notify policy twice about the same ANR.
6383TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006384 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6386 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006387
6388 // Once a focused event arrives, we get an ANR for this application
6389 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6390 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006391 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006392 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6393 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006394 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006395 const std::chrono::duration appTimeout =
6396 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6397 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006398
Vishnu Naire4df8752022-09-08 09:17:55 -07006399 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006400 // ANR should not be raised again. It is up to policy to do that if it desires.
6401 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006402
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006403 // If we now get a focused window, the ANR should stop, but the policy handles that via
6404 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006405 ASSERT_TRUE(mDispatcher->waitForIdle());
6406}
6407
6408// We have a focused application, but no focused window
6409TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006410 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6412 mWindow->consumeFocusEvent(false);
6413
6414 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006415 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006416 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006417 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6418 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006419
Vishnu Naire4df8752022-09-08 09:17:55 -07006420 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6421 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006422
6423 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006424 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006425 ASSERT_TRUE(mDispatcher->waitForIdle());
6426 mWindow->assertNoEvents();
6427}
6428
6429/**
6430 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6431 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6432 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6433 * the ANR mechanism should still work.
6434 *
6435 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6436 * DOWN event, while not responding on the second one.
6437 */
6438TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6439 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6440 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6441 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6442 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6443 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006444 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006445
6446 // Now send ACTION_UP, with identical timestamp
6447 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6448 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6449 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6450 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006451 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006452
6453 // We have now sent down and up. Let's consume first event and then ANR on the second.
6454 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6455 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006456 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006457}
6458
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006459// A spy window can receive an ANR
6460TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6461 sp<FakeWindowHandle> spy = addSpyWindow();
6462
6463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6464 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6465 WINDOW_LOCATION));
6466 mWindow->consumeMotionDown();
6467
6468 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6469 ASSERT_TRUE(sequenceNum);
6470 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006471 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006472
6473 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006474 spy->consumeMotionEvent(
6475 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006476 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006477 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006478}
6479
6480// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006481// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006482TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6483 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006484
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6486 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006487 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006489
6490 // Stuck on the ACTION_UP
6491 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006492 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006493
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006494 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006495 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006496 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6497 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006498
6499 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6500 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006501 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006502 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006503 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006504}
6505
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006506// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006507// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006508TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6509 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006510
6511 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006512 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6513 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006514
6515 mWindow->consumeMotionDown();
6516 // Stuck on the ACTION_UP
6517 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006518 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006519
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006520 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006521 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006522 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6523 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006524
6525 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6526 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006527 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006528 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006529 spy->assertNoEvents();
6530}
6531
6532TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6533 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6534
6535 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6536
6537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6538 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6539 WINDOW_LOCATION));
6540
6541 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6542 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6543 ASSERT_TRUE(consumeSeq);
6544
Prabir Pradhanedd96402022-02-15 01:46:16 -08006545 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006546
6547 monitor.finishEvent(*consumeSeq);
6548 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6549
6550 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006551 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006552}
6553
6554// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6555// process events, you don't get an anr. When the window later becomes unresponsive again, you
6556// get an ANR again.
6557// 1. tap -> block on ACTION_UP -> receive ANR
6558// 2. consume all pending events (= queue becomes healthy again)
6559// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6560TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6561 tapOnWindow();
6562
6563 mWindow->consumeMotionDown();
6564 // Block on ACTION_UP
6565 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006566 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006567 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6568 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006569 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006570 mWindow->assertNoEvents();
6571
6572 tapOnWindow();
6573 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006574 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006575 mWindow->consumeMotionUp();
6576
6577 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006578 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006579 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006580 mWindow->assertNoEvents();
6581}
6582
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006583// If a connection remains unresponsive for a while, make sure policy is only notified once about
6584// it.
6585TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006587 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6588 WINDOW_LOCATION));
6589
6590 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006591 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006592 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006593 // 'notifyConnectionUnresponsive' should only be called once per connection
6594 mFakePolicy->assertNotifyAnrWasNotCalled();
6595 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006596 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006597 mWindow->consumeMotionEvent(
6598 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006599 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006600 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006601 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006602 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006603}
6604
6605/**
6606 * If a window is processing a motion event, and then a key event comes in, the key event should
6607 * not to to the focused window until the motion is processed.
6608 *
6609 * Warning!!!
6610 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6611 * and the injection timeout that we specify when injecting the key.
6612 * We must have the injection timeout (10ms) be smaller than
6613 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6614 *
6615 * If that value changes, this test should also change.
6616 */
6617TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6618 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6620
6621 tapOnWindow();
6622 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6623 ASSERT_TRUE(downSequenceNum);
6624 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6625 ASSERT_TRUE(upSequenceNum);
6626 // Don't finish the events yet, and send a key
6627 // Injection will "succeed" because we will eventually give up and send the key to the focused
6628 // window even if motions are still being processed. But because the injection timeout is short,
6629 // we will receive INJECTION_TIMED_OUT as the result.
6630
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006631 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006632 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006633 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6634 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006635 // Key will not be sent to the window, yet, because the window is still processing events
6636 // and the key remains pending, waiting for the touch events to be processed
6637 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6638 ASSERT_FALSE(keySequenceNum);
6639
6640 std::this_thread::sleep_for(500ms);
6641 // if we wait long enough though, dispatcher will give up, and still send the key
6642 // to the focused window, even though we have not yet finished the motion event
6643 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6644 mWindow->finishEvent(*downSequenceNum);
6645 mWindow->finishEvent(*upSequenceNum);
6646}
6647
6648/**
6649 * If a window is processing a motion event, and then a key event comes in, the key event should
6650 * not go to the focused window until the motion is processed.
6651 * If then a new motion comes in, then the pending key event should be going to the currently
6652 * focused window right away.
6653 */
6654TEST_F(InputDispatcherSingleWindowAnr,
6655 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6656 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6658
6659 tapOnWindow();
6660 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6661 ASSERT_TRUE(downSequenceNum);
6662 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6663 ASSERT_TRUE(upSequenceNum);
6664 // Don't finish the events yet, and send a key
6665 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006667 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6668 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006669 // At this point, key is still pending, and should not be sent to the application yet.
6670 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6671 ASSERT_FALSE(keySequenceNum);
6672
6673 // Now tap down again. It should cause the pending key to go to the focused window right away.
6674 tapOnWindow();
6675 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6676 // the other events yet. We can finish events in any order.
6677 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6678 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6679 mWindow->consumeMotionDown();
6680 mWindow->consumeMotionUp();
6681 mWindow->assertNoEvents();
6682}
6683
6684class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6685 virtual void SetUp() override {
6686 InputDispatcherTest::SetUp();
6687
Chris Yea209fde2020-07-22 13:54:51 -07006688 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006689 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006690 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6691 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006692 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006693 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006694 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006695
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006696 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6697 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006698 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006699 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006700
6701 // Set focused application.
6702 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006703 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006704
6705 // Expect one focus window exist in display.
6706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006707 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006708 mFocusedWindow->consumeFocusEvent(true);
6709 }
6710
6711 virtual void TearDown() override {
6712 InputDispatcherTest::TearDown();
6713
6714 mUnfocusedWindow.clear();
6715 mFocusedWindow.clear();
6716 }
6717
6718protected:
Chris Yea209fde2020-07-22 13:54:51 -07006719 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006720 sp<FakeWindowHandle> mUnfocusedWindow;
6721 sp<FakeWindowHandle> mFocusedWindow;
6722 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6723 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6724 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6725
6726 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6727
6728 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6729
6730private:
6731 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6734 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006736 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6737 location));
6738 }
6739};
6740
6741// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6742// should be ANR'd first.
6743TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006744 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006745 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6746 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006747 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006748 mFocusedWindow->consumeMotionDown();
6749 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006750 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006751 // We consumed all events, so no ANR
6752 ASSERT_TRUE(mDispatcher->waitForIdle());
6753 mFakePolicy->assertNotifyAnrWasNotCalled();
6754
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006756 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6757 FOCUSED_WINDOW_LOCATION));
6758 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6759 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006760
6761 const std::chrono::duration timeout =
6762 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006763 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006764 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6765 // sequence to make it consistent
6766 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006767 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006768 mFocusedWindow->consumeMotionDown();
6769 // This cancel is generated because the connection was unresponsive
6770 mFocusedWindow->consumeMotionCancel();
6771 mFocusedWindow->assertNoEvents();
6772 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006773 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006774 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6775 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006776 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006777}
6778
6779// If we have 2 windows with identical timeouts that are both unresponsive,
6780// it doesn't matter which order they should have ANR.
6781// But we should receive ANR for both.
6782TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6783 // Set the timeout for unfocused window to match the focused window
6784 mUnfocusedWindow->setDispatchingTimeout(10ms);
6785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6786
6787 tapOnFocusedWindow();
6788 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006789 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6790 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6791 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006792
6793 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006794 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6795 mFocusedWindow->getToken() == anrConnectionToken2);
6796 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6797 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006798
6799 ASSERT_TRUE(mDispatcher->waitForIdle());
6800 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006801
6802 mFocusedWindow->consumeMotionDown();
6803 mFocusedWindow->consumeMotionUp();
6804 mUnfocusedWindow->consumeMotionOutside();
6805
Prabir Pradhanedd96402022-02-15 01:46:16 -08006806 sp<IBinder> responsiveToken1, responsiveToken2;
6807 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6808 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006809
6810 // Both applications should be marked as responsive, in any order
6811 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6812 mFocusedWindow->getToken() == responsiveToken2);
6813 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6814 mUnfocusedWindow->getToken() == responsiveToken2);
6815 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006816}
6817
6818// If a window is already not responding, the second tap on the same window should be ignored.
6819// We should also log an error to account for the dropped event (not tested here).
6820// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6821TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6822 tapOnFocusedWindow();
6823 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006824 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006825 // Receive the events, but don't respond
6826 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6827 ASSERT_TRUE(downEventSequenceNum);
6828 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6829 ASSERT_TRUE(upEventSequenceNum);
6830 const std::chrono::duration timeout =
6831 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006832 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006833
6834 // Tap once again
6835 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006836 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6838 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006839 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006840 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6841 FOCUSED_WINDOW_LOCATION));
6842 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6843 // valid touch target
6844 mUnfocusedWindow->assertNoEvents();
6845
6846 // Consume the first tap
6847 mFocusedWindow->finishEvent(*downEventSequenceNum);
6848 mFocusedWindow->finishEvent(*upEventSequenceNum);
6849 ASSERT_TRUE(mDispatcher->waitForIdle());
6850 // The second tap did not go to the focused window
6851 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006852 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006853 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6854 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006855 mFakePolicy->assertNotifyAnrWasNotCalled();
6856}
6857
6858// If you tap outside of all windows, there will not be ANR
6859TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006860 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006861 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6862 LOCATION_OUTSIDE_ALL_WINDOWS));
6863 ASSERT_TRUE(mDispatcher->waitForIdle());
6864 mFakePolicy->assertNotifyAnrWasNotCalled();
6865}
6866
6867// Since the focused window is paused, tapping on it should not produce any events
6868TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6869 mFocusedWindow->setPaused(true);
6870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6871
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006872 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006873 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6874 FOCUSED_WINDOW_LOCATION));
6875
6876 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6877 ASSERT_TRUE(mDispatcher->waitForIdle());
6878 // Should not ANR because the window is paused, and touches shouldn't go to it
6879 mFakePolicy->assertNotifyAnrWasNotCalled();
6880
6881 mFocusedWindow->assertNoEvents();
6882 mUnfocusedWindow->assertNoEvents();
6883}
6884
6885/**
6886 * If a window is processing a motion event, and then a key event comes in, the key event should
6887 * not to to the focused window until the motion is processed.
6888 * If a different window becomes focused at this time, the key should go to that window instead.
6889 *
6890 * Warning!!!
6891 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6892 * and the injection timeout that we specify when injecting the key.
6893 * We must have the injection timeout (10ms) be smaller than
6894 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6895 *
6896 * If that value changes, this test should also change.
6897 */
6898TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6899 // Set a long ANR timeout to prevent it from triggering
6900 mFocusedWindow->setDispatchingTimeout(2s);
6901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6902
6903 tapOnUnfocusedWindow();
6904 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6905 ASSERT_TRUE(downSequenceNum);
6906 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6907 ASSERT_TRUE(upSequenceNum);
6908 // Don't finish the events yet, and send a key
6909 // Injection will succeed because we will eventually give up and send the key to the focused
6910 // window even if motions are still being processed.
6911
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006912 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006913 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6914 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006916 // Key will not be sent to the window, yet, because the window is still processing events
6917 // and the key remains pending, waiting for the touch events to be processed
6918 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6919 ASSERT_FALSE(keySequenceNum);
6920
6921 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006922 mFocusedWindow->setFocusable(false);
6923 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006925 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006926
6927 // Focus events should precede the key events
6928 mUnfocusedWindow->consumeFocusEvent(true);
6929 mFocusedWindow->consumeFocusEvent(false);
6930
6931 // Finish the tap events, which should unblock dispatcher
6932 mUnfocusedWindow->finishEvent(*downSequenceNum);
6933 mUnfocusedWindow->finishEvent(*upSequenceNum);
6934
6935 // Now that all queues are cleared and no backlog in the connections, the key event
6936 // can finally go to the newly focused "mUnfocusedWindow".
6937 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6938 mFocusedWindow->assertNoEvents();
6939 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006940 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006941}
6942
6943// When the touch stream is split across 2 windows, and one of them does not respond,
6944// then ANR should be raised and the touch should be canceled for the unresponsive window.
6945// The other window should not be affected by that.
6946TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6947 // Touch Window 1
6948 NotifyMotionArgs motionArgs =
6949 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6950 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6951 mDispatcher->notifyMotion(&motionArgs);
6952 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006953 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006954
6955 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006956 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6957 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006958 mDispatcher->notifyMotion(&motionArgs);
6959
6960 const std::chrono::duration timeout =
6961 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006962 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006963
6964 mUnfocusedWindow->consumeMotionDown();
6965 mFocusedWindow->consumeMotionDown();
6966 // Focused window may or may not receive ACTION_MOVE
6967 // But it should definitely receive ACTION_CANCEL due to the ANR
6968 InputEvent* event;
6969 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6970 ASSERT_TRUE(moveOrCancelSequenceNum);
6971 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6972 ASSERT_NE(nullptr, event);
6973 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6974 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6975 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6976 mFocusedWindow->consumeMotionCancel();
6977 } else {
6978 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6979 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006980 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006981 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6982 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006983
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006984 mUnfocusedWindow->assertNoEvents();
6985 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006986 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006987}
6988
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006989/**
6990 * If we have no focused window, and a key comes in, we start the ANR timer.
6991 * The focused application should add a focused window before the timer runs out to prevent ANR.
6992 *
6993 * If the user touches another application during this time, the key should be dropped.
6994 * Next, if a new focused window comes in, without toggling the focused application,
6995 * then no ANR should occur.
6996 *
6997 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6998 * but in some cases the policy may not update the focused application.
6999 */
7000TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
7001 std::shared_ptr<FakeApplicationHandle> focusedApplication =
7002 std::make_shared<FakeApplicationHandle>();
7003 focusedApplication->setDispatchingTimeout(60ms);
7004 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
7005 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
7006 mFocusedWindow->setFocusable(false);
7007
7008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7009 mFocusedWindow->consumeFocusEvent(false);
7010
7011 // Send a key. The ANR timer should start because there is no focused window.
7012 // 'focusedApplication' will get blamed if this timer completes.
7013 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007014 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00007015 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7016 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
7017 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007019
7020 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
7021 // then the injected touches won't cause the focused event to get dropped.
7022 // The dispatcher only checks for whether the queue should be pruned upon queueing.
7023 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
7024 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
7025 // For this test, it means that the key would get delivered to the window once it becomes
7026 // focused.
7027 std::this_thread::sleep_for(10ms);
7028
7029 // Touch unfocused window. This should force the pending key to get dropped.
7030 NotifyMotionArgs motionArgs =
7031 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7032 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
7033 mDispatcher->notifyMotion(&motionArgs);
7034
7035 // We do not consume the motion right away, because that would require dispatcher to first
7036 // process (== drop) the key event, and by that time, ANR will be raised.
7037 // Set the focused window first.
7038 mFocusedWindow->setFocusable(true);
7039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7040 setFocusedWindow(mFocusedWindow);
7041 mFocusedWindow->consumeFocusEvent(true);
7042 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
7043 // to another application. This could be a bug / behaviour in the policy.
7044
7045 mUnfocusedWindow->consumeMotionDown();
7046
7047 ASSERT_TRUE(mDispatcher->waitForIdle());
7048 // Should not ANR because we actually have a focused window. It was just added too slowly.
7049 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
7050}
7051
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007052// These tests ensure we cannot send touch events to a window that's positioned behind a window
7053// that has feature NO_INPUT_CHANNEL.
7054// Layout:
7055// Top (closest to user)
7056// mNoInputWindow (above all windows)
7057// mBottomWindow
7058// Bottom (furthest from user)
7059class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
7060 virtual void SetUp() override {
7061 InputDispatcherTest::SetUp();
7062
7063 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007064 mNoInputWindow =
7065 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7066 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00007067 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007068 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007069 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7070 // It's perfectly valid for this window to not have an associated input channel
7071
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007072 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
7073 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007074 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
7075
7076 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7077 }
7078
7079protected:
7080 std::shared_ptr<FakeApplicationHandle> mApplication;
7081 sp<FakeWindowHandle> mNoInputWindow;
7082 sp<FakeWindowHandle> mBottomWindow;
7083};
7084
7085TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
7086 PointF touchedPoint = {10, 10};
7087
7088 NotifyMotionArgs motionArgs =
7089 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7090 ADISPLAY_ID_DEFAULT, {touchedPoint});
7091 mDispatcher->notifyMotion(&motionArgs);
7092
7093 mNoInputWindow->assertNoEvents();
7094 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
7095 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
7096 // and therefore should prevent mBottomWindow from receiving touches
7097 mBottomWindow->assertNoEvents();
7098}
7099
7100/**
7101 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
7102 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
7103 */
7104TEST_F(InputDispatcherMultiWindowOcclusionTests,
7105 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007106 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7107 "Window with input channel and NO_INPUT_CHANNEL",
7108 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007109
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007110 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007111 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7113
7114 PointF touchedPoint = {10, 10};
7115
7116 NotifyMotionArgs motionArgs =
7117 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7118 ADISPLAY_ID_DEFAULT, {touchedPoint});
7119 mDispatcher->notifyMotion(&motionArgs);
7120
7121 mNoInputWindow->assertNoEvents();
7122 mBottomWindow->assertNoEvents();
7123}
7124
Vishnu Nair958da932020-08-21 17:12:37 -07007125class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7126protected:
7127 std::shared_ptr<FakeApplicationHandle> mApp;
7128 sp<FakeWindowHandle> mWindow;
7129 sp<FakeWindowHandle> mMirror;
7130
7131 virtual void SetUp() override {
7132 InputDispatcherTest::SetUp();
7133 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007134 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7135 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7136 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007137 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7138 mWindow->setFocusable(true);
7139 mMirror->setFocusable(true);
7140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7141 }
7142};
7143
7144TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7145 // Request focus on a mirrored window
7146 setFocusedWindow(mMirror);
7147
7148 // window gets focused
7149 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7151 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007152 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7153}
7154
7155// A focused & mirrored window remains focused only if the window and its mirror are both
7156// focusable.
7157TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7158 setFocusedWindow(mMirror);
7159
7160 // window gets focused
7161 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7163 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007164 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007165 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7166 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007167 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7168
7169 mMirror->setFocusable(false);
7170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7171
7172 // window loses focus since one of the windows associated with the token in not focusable
7173 mWindow->consumeFocusEvent(false);
7174
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007175 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7176 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007177 mWindow->assertNoEvents();
7178}
7179
7180// A focused & mirrored window remains focused until the window and its mirror both become
7181// invisible.
7182TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7183 setFocusedWindow(mMirror);
7184
7185 // window gets focused
7186 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7188 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007189 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7191 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007192 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7193
7194 mMirror->setVisible(false);
7195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7196
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7198 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007199 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7201 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007202 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7203
7204 mWindow->setVisible(false);
7205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7206
7207 // window loses focus only after all windows associated with the token become invisible.
7208 mWindow->consumeFocusEvent(false);
7209
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007210 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7211 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007212 mWindow->assertNoEvents();
7213}
7214
7215// A focused & mirrored window remains focused until both windows are removed.
7216TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7217 setFocusedWindow(mMirror);
7218
7219 // window gets focused
7220 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7222 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007223 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007224 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7225 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007226 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7227
7228 // single window is removed but the window token remains focused
7229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7230
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7232 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007233 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7235 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007236 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7237
7238 // Both windows are removed
7239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7240 mWindow->consumeFocusEvent(false);
7241
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007242 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7243 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007244 mWindow->assertNoEvents();
7245}
7246
7247// Focus request can be pending until one window becomes visible.
7248TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7249 // Request focus on an invisible mirror.
7250 mWindow->setVisible(false);
7251 mMirror->setVisible(false);
7252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7253 setFocusedWindow(mMirror);
7254
7255 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007256 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007257 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7258 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007259
7260 mMirror->setVisible(true);
7261 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7262
7263 // window gets focused
7264 mWindow->consumeFocusEvent(true);
7265 // window gets the pending key event
7266 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7267}
Prabir Pradhan99987712020-11-10 18:43:05 -08007268
7269class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7270protected:
7271 std::shared_ptr<FakeApplicationHandle> mApp;
7272 sp<FakeWindowHandle> mWindow;
7273 sp<FakeWindowHandle> mSecondWindow;
7274
7275 void SetUp() override {
7276 InputDispatcherTest::SetUp();
7277 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007278 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007279 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007280 mSecondWindow =
7281 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007282 mSecondWindow->setFocusable(true);
7283
7284 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7285 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7286
7287 setFocusedWindow(mWindow);
7288 mWindow->consumeFocusEvent(true);
7289 }
7290
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007291 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7292 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007293 mDispatcher->notifyPointerCaptureChanged(&args);
7294 }
7295
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007296 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7297 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007298 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007299 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7300 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007301 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007302 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007303 }
7304};
7305
7306TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7307 // Ensure that capture cannot be obtained for unfocused windows.
7308 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7309 mFakePolicy->assertSetPointerCaptureNotCalled();
7310 mSecondWindow->assertNoEvents();
7311
7312 // Ensure that capture can be enabled from the focus window.
7313 requestAndVerifyPointerCapture(mWindow, true);
7314
7315 // Ensure that capture cannot be disabled from a window that does not have capture.
7316 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7317 mFakePolicy->assertSetPointerCaptureNotCalled();
7318
7319 // Ensure that capture can be disabled from the window with capture.
7320 requestAndVerifyPointerCapture(mWindow, false);
7321}
7322
7323TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007324 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007325
7326 setFocusedWindow(mSecondWindow);
7327
7328 // Ensure that the capture disabled event was sent first.
7329 mWindow->consumeCaptureEvent(false);
7330 mWindow->consumeFocusEvent(false);
7331 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007332 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007333
7334 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007335 notifyPointerCaptureChanged({});
7336 notifyPointerCaptureChanged(request);
7337 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007338 mWindow->assertNoEvents();
7339 mSecondWindow->assertNoEvents();
7340 mFakePolicy->assertSetPointerCaptureNotCalled();
7341}
7342
7343TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007344 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007345
7346 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007347 notifyPointerCaptureChanged({});
7348 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007349
7350 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007351 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007352 mWindow->consumeCaptureEvent(false);
7353 mWindow->assertNoEvents();
7354}
7355
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007356TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7357 requestAndVerifyPointerCapture(mWindow, true);
7358
7359 // The first window loses focus.
7360 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007361 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007362 mWindow->consumeCaptureEvent(false);
7363
7364 // Request Pointer Capture from the second window before the notification from InputReader
7365 // arrives.
7366 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007367 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007368
7369 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007370 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007371
7372 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007373 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007374
7375 mSecondWindow->consumeFocusEvent(true);
7376 mSecondWindow->consumeCaptureEvent(true);
7377}
7378
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007379TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7380 // App repeatedly enables and disables capture.
7381 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7382 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7383 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7384 mFakePolicy->assertSetPointerCaptureCalled(false);
7385 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7386 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7387
7388 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7389 // first request is now stale, this should do nothing.
7390 notifyPointerCaptureChanged(firstRequest);
7391 mWindow->assertNoEvents();
7392
7393 // InputReader notifies that the second request was enabled.
7394 notifyPointerCaptureChanged(secondRequest);
7395 mWindow->consumeCaptureEvent(true);
7396}
7397
Prabir Pradhan7092e262022-05-03 16:51:09 +00007398TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7399 requestAndVerifyPointerCapture(mWindow, true);
7400
7401 // App toggles pointer capture off and on.
7402 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7403 mFakePolicy->assertSetPointerCaptureCalled(false);
7404
7405 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7406 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7407
7408 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7409 // preceding "disable" request.
7410 notifyPointerCaptureChanged(enableRequest);
7411
7412 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7413 // any notifications.
7414 mWindow->assertNoEvents();
7415}
7416
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007417class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7418protected:
7419 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007420
7421 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7422 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7423
7424 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7425 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7426
7427 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7428 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7429 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7430 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7431 MAXIMUM_OBSCURING_OPACITY);
7432
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007433 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007434 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007435 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007436
7437 sp<FakeWindowHandle> mTouchWindow;
7438
7439 virtual void SetUp() override {
7440 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007441 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007442 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7443 }
7444
7445 virtual void TearDown() override {
7446 InputDispatcherTest::TearDown();
7447 mTouchWindow.clear();
7448 }
7449
chaviw3277faf2021-05-19 16:45:23 -05007450 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7451 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007452 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007453 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007454 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007455 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007456 return window;
7457 }
7458
7459 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7460 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7461 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007462 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007463 // Generate an arbitrary PID based on the UID
7464 window->setOwnerInfo(1777 + (uid % 10000), uid);
7465 return window;
7466 }
7467
7468 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7469 NotifyMotionArgs args =
7470 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7471 ADISPLAY_ID_DEFAULT, points);
7472 mDispatcher->notifyMotion(&args);
7473 }
7474};
7475
7476TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007477 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007478 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007480
7481 touch();
7482
7483 mTouchWindow->assertNoEvents();
7484}
7485
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007486TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007487 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7488 const sp<FakeWindowHandle>& w =
7489 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7491
7492 touch();
7493
7494 mTouchWindow->assertNoEvents();
7495}
7496
7497TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007498 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7499 const sp<FakeWindowHandle>& w =
7500 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7502
7503 touch();
7504
7505 w->assertNoEvents();
7506}
7507
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007508TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007509 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007511
7512 touch();
7513
7514 mTouchWindow->consumeAnyMotionDown();
7515}
7516
7517TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007518 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007519 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007520 w->setFrame(Rect(0, 0, 50, 50));
7521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007522
7523 touch({PointF{100, 100}});
7524
7525 mTouchWindow->consumeAnyMotionDown();
7526}
7527
7528TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007529 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007530 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7532
7533 touch();
7534
7535 mTouchWindow->consumeAnyMotionDown();
7536}
7537
7538TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7539 const sp<FakeWindowHandle>& w =
7540 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007542
7543 touch();
7544
7545 mTouchWindow->consumeAnyMotionDown();
7546}
7547
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007548TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7549 const sp<FakeWindowHandle>& w =
7550 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7552
7553 touch();
7554
7555 w->assertNoEvents();
7556}
7557
7558/**
7559 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7560 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7561 * window, the occluding window will still receive ACTION_OUTSIDE event.
7562 */
7563TEST_F(InputDispatcherUntrustedTouchesTest,
7564 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7565 const sp<FakeWindowHandle>& w =
7566 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007567 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7569
7570 touch();
7571
7572 w->consumeMotionOutside();
7573}
7574
7575TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7576 const sp<FakeWindowHandle>& w =
7577 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007578 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7580
7581 touch();
7582
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007583 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007584}
7585
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007586TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007587 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007588 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7589 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7591
7592 touch();
7593
7594 mTouchWindow->consumeAnyMotionDown();
7595}
7596
7597TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7598 const sp<FakeWindowHandle>& w =
7599 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7600 MAXIMUM_OBSCURING_OPACITY);
7601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007602
7603 touch();
7604
7605 mTouchWindow->consumeAnyMotionDown();
7606}
7607
7608TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007609 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7611 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7613
7614 touch();
7615
7616 mTouchWindow->assertNoEvents();
7617}
7618
7619TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7620 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7621 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007622 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7623 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007624 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007625 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7626 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7628
7629 touch();
7630
7631 mTouchWindow->assertNoEvents();
7632}
7633
7634TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7635 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7636 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007637 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7638 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007639 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007640 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7641 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7643
7644 touch();
7645
7646 mTouchWindow->consumeAnyMotionDown();
7647}
7648
7649TEST_F(InputDispatcherUntrustedTouchesTest,
7650 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7651 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007652 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7653 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007654 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007655 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7656 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7658
7659 touch();
7660
7661 mTouchWindow->consumeAnyMotionDown();
7662}
7663
7664TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7665 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007666 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7667 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007668 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007669 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7670 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007672
7673 touch();
7674
7675 mTouchWindow->assertNoEvents();
7676}
7677
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007678TEST_F(InputDispatcherUntrustedTouchesTest,
7679 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7680 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007681 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7682 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007683 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7685 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7687
7688 touch();
7689
7690 mTouchWindow->assertNoEvents();
7691}
7692
7693TEST_F(InputDispatcherUntrustedTouchesTest,
7694 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7695 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007696 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7697 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007698 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007699 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7700 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7702
7703 touch();
7704
7705 mTouchWindow->consumeAnyMotionDown();
7706}
7707
7708TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7709 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007710 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7711 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7713
7714 touch();
7715
7716 mTouchWindow->consumeAnyMotionDown();
7717}
7718
7719TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7720 const sp<FakeWindowHandle>& w =
7721 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7723
7724 touch();
7725
7726 mTouchWindow->consumeAnyMotionDown();
7727}
7728
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007729TEST_F(InputDispatcherUntrustedTouchesTest,
7730 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7731 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7732 const sp<FakeWindowHandle>& w =
7733 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7735
7736 touch();
7737
7738 mTouchWindow->assertNoEvents();
7739}
7740
7741TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7742 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7743 const sp<FakeWindowHandle>& w =
7744 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7746
7747 touch();
7748
7749 mTouchWindow->consumeAnyMotionDown();
7750}
7751
7752TEST_F(InputDispatcherUntrustedTouchesTest,
7753 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7754 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7755 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007756 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7757 OPACITY_ABOVE_THRESHOLD);
7758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7759
7760 touch();
7761
7762 mTouchWindow->consumeAnyMotionDown();
7763}
7764
7765TEST_F(InputDispatcherUntrustedTouchesTest,
7766 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7767 const sp<FakeWindowHandle>& w1 =
7768 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7769 OPACITY_BELOW_THRESHOLD);
7770 const sp<FakeWindowHandle>& w2 =
7771 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7772 OPACITY_BELOW_THRESHOLD);
7773 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7774
7775 touch();
7776
7777 mTouchWindow->assertNoEvents();
7778}
7779
7780/**
7781 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7782 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7783 * (which alone would result in allowing touches) does not affect the blocking behavior.
7784 */
7785TEST_F(InputDispatcherUntrustedTouchesTest,
7786 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7787 const sp<FakeWindowHandle>& wB =
7788 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7789 OPACITY_BELOW_THRESHOLD);
7790 const sp<FakeWindowHandle>& wC =
7791 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7792 OPACITY_BELOW_THRESHOLD);
7793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7794
7795 touch();
7796
7797 mTouchWindow->assertNoEvents();
7798}
7799
7800/**
7801 * This test is testing that a window from a different UID but with same application token doesn't
7802 * block the touch. Apps can share the application token for close UI collaboration for example.
7803 */
7804TEST_F(InputDispatcherUntrustedTouchesTest,
7805 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7806 const sp<FakeWindowHandle>& w =
7807 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7808 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7810
7811 touch();
7812
7813 mTouchWindow->consumeAnyMotionDown();
7814}
7815
arthurhungb89ccb02020-12-30 16:19:01 +08007816class InputDispatcherDragTests : public InputDispatcherTest {
7817protected:
7818 std::shared_ptr<FakeApplicationHandle> mApp;
7819 sp<FakeWindowHandle> mWindow;
7820 sp<FakeWindowHandle> mSecondWindow;
7821 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007822 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007823 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7824 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007825
7826 void SetUp() override {
7827 InputDispatcherTest::SetUp();
7828 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007829 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007830 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007831
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007832 mSecondWindow =
7833 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007834 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007835
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007836 mSpyWindow =
7837 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007838 mSpyWindow->setSpy(true);
7839 mSpyWindow->setTrustedOverlay(true);
7840 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7841
arthurhungb89ccb02020-12-30 16:19:01 +08007842 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007844 }
7845
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007846 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7847 switch (fromSource) {
7848 case AINPUT_SOURCE_TOUCHSCREEN:
7849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7851 ADISPLAY_ID_DEFAULT, {50, 50}))
7852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7853 break;
7854 case AINPUT_SOURCE_STYLUS:
7855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7856 injectMotionEvent(
7857 mDispatcher,
7858 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7859 AINPUT_SOURCE_STYLUS)
7860 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7861 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7862 .x(50)
7863 .y(50))
7864 .build()));
7865 break;
7866 case AINPUT_SOURCE_MOUSE:
7867 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7868 injectMotionEvent(
7869 mDispatcher,
7870 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7871 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7872 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7873 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7874 .x(50)
7875 .y(50))
7876 .build()));
7877 break;
7878 default:
7879 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7880 }
arthurhungb89ccb02020-12-30 16:19:01 +08007881
7882 // Window should receive motion event.
7883 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007884 // Spy window should also receive motion event
7885 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007886 }
7887
7888 // Start performing drag, we will create a drag window and transfer touch to it.
7889 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7890 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007891 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007892 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007893 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007894 }
arthurhungb89ccb02020-12-30 16:19:01 +08007895
7896 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007897 mDragWindow =
7898 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007899 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007900 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007901 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007902
7903 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007904 bool transferred =
7905 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007906 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007907 if (transferred) {
7908 mWindow->consumeMotionCancel();
7909 mDragWindow->consumeMotionDown();
7910 }
7911 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007912 }
7913};
7914
7915TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007916 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007917
7918 // Move on window.
7919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7920 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7921 ADISPLAY_ID_DEFAULT, {50, 50}))
7922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7923 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7924 mWindow->consumeDragEvent(false, 50, 50);
7925 mSecondWindow->assertNoEvents();
7926
7927 // Move to another window.
7928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7929 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7930 ADISPLAY_ID_DEFAULT, {150, 50}))
7931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7932 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7933 mWindow->consumeDragEvent(true, 150, 50);
7934 mSecondWindow->consumeDragEvent(false, 50, 50);
7935
7936 // Move back to original window.
7937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7938 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7939 ADISPLAY_ID_DEFAULT, {50, 50}))
7940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7941 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7942 mWindow->consumeDragEvent(false, 50, 50);
7943 mSecondWindow->consumeDragEvent(true, -50, 50);
7944
7945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7946 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7948 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7949 mWindow->assertNoEvents();
7950 mSecondWindow->assertNoEvents();
7951}
7952
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007953TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007954 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007955
7956 // No cancel event after drag start
7957 mSpyWindow->assertNoEvents();
7958
7959 const MotionEvent secondFingerDownEvent =
7960 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7961 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007962 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7963 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007964 .build();
7965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7966 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7967 InputEventInjectionSync::WAIT_FOR_RESULT))
7968 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7969
7970 // Receives cancel for first pointer after next pointer down
7971 mSpyWindow->consumeMotionCancel();
7972 mSpyWindow->consumeMotionDown();
7973
7974 mSpyWindow->assertNoEvents();
7975}
7976
arthurhungf452d0b2021-01-06 00:19:52 +08007977TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007978 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007979
7980 // Move on window.
7981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7982 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7983 ADISPLAY_ID_DEFAULT, {50, 50}))
7984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7985 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7986 mWindow->consumeDragEvent(false, 50, 50);
7987 mSecondWindow->assertNoEvents();
7988
7989 // Move to another window.
7990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7991 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7992 ADISPLAY_ID_DEFAULT, {150, 50}))
7993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7994 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7995 mWindow->consumeDragEvent(true, 150, 50);
7996 mSecondWindow->consumeDragEvent(false, 50, 50);
7997
7998 // drop to another window.
7999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8000 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8001 {150, 50}))
8002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8003 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8004 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8005 mWindow->assertNoEvents();
8006 mSecondWindow->assertNoEvents();
8007}
8008
arthurhung6d4bed92021-03-17 11:59:33 +08008009TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008010 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08008011
8012 // Move on window and keep button pressed.
8013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8014 injectMotionEvent(mDispatcher,
8015 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8016 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
8017 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8018 .x(50)
8019 .y(50))
8020 .build()))
8021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8022 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8023 mWindow->consumeDragEvent(false, 50, 50);
8024 mSecondWindow->assertNoEvents();
8025
8026 // Move to another window and release button, expect to drop item.
8027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8028 injectMotionEvent(mDispatcher,
8029 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8030 .buttonState(0)
8031 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8032 .x(150)
8033 .y(50))
8034 .build()))
8035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8036 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8037 mWindow->assertNoEvents();
8038 mSecondWindow->assertNoEvents();
8039 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8040
8041 // nothing to the window.
8042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8043 injectMotionEvent(mDispatcher,
8044 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
8045 .buttonState(0)
8046 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8047 .x(150)
8048 .y(50))
8049 .build()))
8050 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8051 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8052 mWindow->assertNoEvents();
8053 mSecondWindow->assertNoEvents();
8054}
8055
Arthur Hung54745652022-04-20 07:17:41 +00008056TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008057 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08008058
8059 // Set second window invisible.
8060 mSecondWindow->setVisible(false);
8061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
8062
8063 // Move on window.
8064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8065 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8066 ADISPLAY_ID_DEFAULT, {50, 50}))
8067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8068 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8069 mWindow->consumeDragEvent(false, 50, 50);
8070 mSecondWindow->assertNoEvents();
8071
8072 // Move to another window.
8073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8074 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8075 ADISPLAY_ID_DEFAULT, {150, 50}))
8076 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8077 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8078 mWindow->consumeDragEvent(true, 150, 50);
8079 mSecondWindow->assertNoEvents();
8080
8081 // drop to another window.
8082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8083 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8084 {150, 50}))
8085 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8086 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8087 mFakePolicy->assertDropTargetEquals(nullptr);
8088 mWindow->assertNoEvents();
8089 mSecondWindow->assertNoEvents();
8090}
8091
Arthur Hung54745652022-04-20 07:17:41 +00008092TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008093 // Ensure window could track pointerIds if it didn't support split touch.
8094 mWindow->setPreventSplitting(true);
8095
Arthur Hung54745652022-04-20 07:17:41 +00008096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8097 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8098 {50, 50}))
8099 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8100 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8101
8102 const MotionEvent secondFingerDownEvent =
8103 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8104 .displayId(ADISPLAY_ID_DEFAULT)
8105 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008106 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8107 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008108 .build();
8109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8110 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8111 InputEventInjectionSync::WAIT_FOR_RESULT))
8112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008113 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00008114
8115 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008116 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008117}
8118
8119TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
8120 // First down on second window.
8121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8122 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8123 {150, 50}))
8124 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8125
8126 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8127
8128 // Second down on first window.
8129 const MotionEvent secondFingerDownEvent =
8130 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8131 .displayId(ADISPLAY_ID_DEFAULT)
8132 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008133 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8134 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008135 .build();
8136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8137 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8138 InputEventInjectionSync::WAIT_FOR_RESULT))
8139 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8140 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8141
8142 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008143 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008144
8145 // Move on window.
8146 const MotionEvent secondFingerMoveEvent =
8147 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8148 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008149 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8150 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008151 .build();
8152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8153 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8154 InputEventInjectionSync::WAIT_FOR_RESULT));
8155 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8156 mWindow->consumeDragEvent(false, 50, 50);
8157 mSecondWindow->consumeMotionMove();
8158
8159 // Release the drag pointer should perform drop.
8160 const MotionEvent secondFingerUpEvent =
8161 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8162 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008163 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8164 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008165 .build();
8166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8167 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8168 InputEventInjectionSync::WAIT_FOR_RESULT));
8169 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8170 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8171 mWindow->assertNoEvents();
8172 mSecondWindow->consumeMotionMove();
8173}
8174
Arthur Hung3915c1f2022-05-31 07:17:17 +00008175TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008176 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008177
8178 // Update window of second display.
8179 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008180 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008181 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8182
8183 // Let second display has a touch state.
8184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8185 injectMotionEvent(mDispatcher,
8186 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8187 AINPUT_SOURCE_TOUCHSCREEN)
8188 .displayId(SECOND_DISPLAY_ID)
8189 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8190 .x(100)
8191 .y(100))
8192 .build()));
8193 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008194 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008195 // Update window again.
8196 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8197
8198 // Move on window.
8199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8200 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8201 ADISPLAY_ID_DEFAULT, {50, 50}))
8202 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8203 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8204 mWindow->consumeDragEvent(false, 50, 50);
8205 mSecondWindow->assertNoEvents();
8206
8207 // Move to another window.
8208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8209 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8210 ADISPLAY_ID_DEFAULT, {150, 50}))
8211 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8212 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8213 mWindow->consumeDragEvent(true, 150, 50);
8214 mSecondWindow->consumeDragEvent(false, 50, 50);
8215
8216 // drop to another window.
8217 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8218 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8219 {150, 50}))
8220 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8221 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8222 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8223 mWindow->assertNoEvents();
8224 mSecondWindow->assertNoEvents();
8225}
8226
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008227TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8228 startDrag(true, AINPUT_SOURCE_MOUSE);
8229 // Move on window.
8230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8231 injectMotionEvent(mDispatcher,
8232 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8233 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8234 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8235 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8236 .x(50)
8237 .y(50))
8238 .build()))
8239 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8240 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8241 mWindow->consumeDragEvent(false, 50, 50);
8242 mSecondWindow->assertNoEvents();
8243
8244 // Move to another window.
8245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8246 injectMotionEvent(mDispatcher,
8247 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8248 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8249 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8250 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8251 .x(150)
8252 .y(50))
8253 .build()))
8254 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8255 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8256 mWindow->consumeDragEvent(true, 150, 50);
8257 mSecondWindow->consumeDragEvent(false, 50, 50);
8258
8259 // drop to another window.
8260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8261 injectMotionEvent(mDispatcher,
8262 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8263 .buttonState(0)
8264 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8265 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8266 .x(150)
8267 .y(50))
8268 .build()))
8269 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8270 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8271 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8272 mWindow->assertNoEvents();
8273 mSecondWindow->assertNoEvents();
8274}
8275
Vishnu Nair062a8672021-09-03 16:07:44 -07008276class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8277
8278TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8279 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008280 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8281 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008282 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008283 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8284 window->setFocusable(true);
8285 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8286 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008287 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008288
8289 // With the flag set, window should not get any input
8290 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8291 mDispatcher->notifyKey(&keyArgs);
8292 window->assertNoEvents();
8293
8294 NotifyMotionArgs motionArgs =
8295 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8296 ADISPLAY_ID_DEFAULT);
8297 mDispatcher->notifyMotion(&motionArgs);
8298 window->assertNoEvents();
8299
8300 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008301 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8303
8304 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8305 mDispatcher->notifyKey(&keyArgs);
8306 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8307
8308 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8309 ADISPLAY_ID_DEFAULT);
8310 mDispatcher->notifyMotion(&motionArgs);
8311 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8312 window->assertNoEvents();
8313}
8314
8315TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8316 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8317 std::make_shared<FakeApplicationHandle>();
8318 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008319 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8320 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008321 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8322 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008323 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008324 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008325 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8326 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008327 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008328 window->setOwnerInfo(222, 222);
8329 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8330 window->setFocusable(true);
8331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8332 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008333 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008334
8335 // With the flag set, window should not get any input
8336 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8337 mDispatcher->notifyKey(&keyArgs);
8338 window->assertNoEvents();
8339
8340 NotifyMotionArgs motionArgs =
8341 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8342 ADISPLAY_ID_DEFAULT);
8343 mDispatcher->notifyMotion(&motionArgs);
8344 window->assertNoEvents();
8345
8346 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008347 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8349
8350 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8351 mDispatcher->notifyKey(&keyArgs);
8352 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8353
8354 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8355 ADISPLAY_ID_DEFAULT);
8356 mDispatcher->notifyMotion(&motionArgs);
8357 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8358 window->assertNoEvents();
8359}
8360
8361TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8362 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8363 std::make_shared<FakeApplicationHandle>();
8364 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008365 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8366 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008367 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8368 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008369 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008371 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8372 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008373 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008374 window->setOwnerInfo(222, 222);
8375 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8376 window->setFocusable(true);
8377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8378 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008379 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008380
8381 // With the flag set, window should not get any input
8382 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8383 mDispatcher->notifyKey(&keyArgs);
8384 window->assertNoEvents();
8385
8386 NotifyMotionArgs motionArgs =
8387 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8388 ADISPLAY_ID_DEFAULT);
8389 mDispatcher->notifyMotion(&motionArgs);
8390 window->assertNoEvents();
8391
8392 // When the window is no longer obscured because it went on top, it should get input
8393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8394
8395 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8396 mDispatcher->notifyKey(&keyArgs);
8397 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8398
8399 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8400 ADISPLAY_ID_DEFAULT);
8401 mDispatcher->notifyMotion(&motionArgs);
8402 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8403 window->assertNoEvents();
8404}
8405
Antonio Kantekf16f2832021-09-28 04:39:20 +00008406class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8407protected:
8408 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008409 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008410 sp<FakeWindowHandle> mWindow;
8411 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008412 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008413
8414 void SetUp() override {
8415 InputDispatcherTest::SetUp();
8416
8417 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008418 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008419 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008420 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008421 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008422 mSecondWindow =
8423 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008424 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008425 mThirdWindow =
8426 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8427 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8428 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008429
8430 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8432 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8433 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008434 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008435
Antonio Kantek15beb512022-06-13 22:35:41 +00008436 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008437 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008438 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008439 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8440 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008441 mThirdWindow->assertNoEvents();
8442 }
8443
8444 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8445 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008446 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008447 SECOND_DISPLAY_ID)) {
8448 mWindow->assertNoEvents();
8449 mSecondWindow->assertNoEvents();
8450 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008451 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008452 }
8453
Antonio Kantek15beb512022-06-13 22:35:41 +00008454 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8455 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008456 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8457 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008458 mWindow->consumeTouchModeEvent(inTouchMode);
8459 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008460 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008461 }
8462};
8463
Antonio Kantek26defcf2022-02-08 01:12:27 +00008464TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008465 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008466 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8467 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008468 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008469}
8470
Antonio Kantek26defcf2022-02-08 01:12:27 +00008471TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8472 const WindowInfo& windowInfo = *mWindow->getInfo();
8473 int32_t ownerPid = windowInfo.ownerPid;
8474 int32_t ownerUid = windowInfo.ownerUid;
8475 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8476 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008477 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008478 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008479 mWindow->assertNoEvents();
8480 mSecondWindow->assertNoEvents();
8481}
8482
8483TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8484 const WindowInfo& windowInfo = *mWindow->getInfo();
8485 int32_t ownerPid = windowInfo.ownerPid;
8486 int32_t ownerUid = windowInfo.ownerUid;
8487 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008488 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008489 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008490}
8491
Antonio Kantekf16f2832021-09-28 04:39:20 +00008492TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008493 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008494 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8495 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008496 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008497 mWindow->assertNoEvents();
8498 mSecondWindow->assertNoEvents();
8499}
8500
Antonio Kantek15beb512022-06-13 22:35:41 +00008501TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8502 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8503 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8504 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008505 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008506 mWindow->assertNoEvents();
8507 mSecondWindow->assertNoEvents();
8508 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8509}
8510
Antonio Kantek48710e42022-03-24 14:19:30 -07008511TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8512 // Interact with the window first.
8513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8514 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8515 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8516
8517 // Then remove focus.
8518 mWindow->setFocusable(false);
8519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8520
8521 // Assert that caller can switch touch mode by owning one of the last interacted window.
8522 const WindowInfo& windowInfo = *mWindow->getInfo();
8523 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8524 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008525 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008526}
8527
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008528class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8529public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008530 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008531 std::shared_ptr<FakeApplicationHandle> application =
8532 std::make_shared<FakeApplicationHandle>();
8533 std::string name = "Fake Spy ";
8534 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008535 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8536 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008537 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008538 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008539 return spy;
8540 }
8541
8542 sp<FakeWindowHandle> createForeground() {
8543 std::shared_ptr<FakeApplicationHandle> application =
8544 std::make_shared<FakeApplicationHandle>();
8545 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008546 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8547 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008548 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008549 return window;
8550 }
8551
8552private:
8553 int mSpyCount{0};
8554};
8555
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008556using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008557/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008558 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8559 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008560TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8561 ScopedSilentDeath _silentDeath;
8562
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008563 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008564 spy->setTrustedOverlay(false);
8565 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8566 ".* not a trusted overlay");
8567}
8568
8569/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008570 * Input injection into a display with a spy window but no foreground windows should succeed.
8571 */
8572TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008573 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8575
8576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8577 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8579 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8580}
8581
8582/**
8583 * Verify the order in which different input windows receive events. The touched foreground window
8584 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8585 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8586 * receive events before ones belows it.
8587 *
8588 * Here, we set up a scenario with four windows in the following Z order from the top:
8589 * spy1, spy2, window, spy3.
8590 * We then inject an event and verify that the foreground "window" receives it first, followed by
8591 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8592 * window.
8593 */
8594TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8595 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008596 auto spy1 = createSpy();
8597 auto spy2 = createSpy();
8598 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8600 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8601 const size_t numChannels = channels.size();
8602
Michael Wright8e9a8562022-02-09 13:44:29 +00008603 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008604 if (!epollFd.ok()) {
8605 FAIL() << "Failed to create epoll fd";
8606 }
8607
8608 for (size_t i = 0; i < numChannels; i++) {
8609 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8610 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8611 FAIL() << "Failed to add fd to epoll";
8612 }
8613 }
8614
8615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8616 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8618
8619 std::vector<size_t> eventOrder;
8620 std::vector<struct epoll_event> events(numChannels);
8621 for (;;) {
8622 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8623 (100ms).count());
8624 if (nFds < 0) {
8625 FAIL() << "Failed to call epoll_wait";
8626 }
8627 if (nFds == 0) {
8628 break; // epoll_wait timed out
8629 }
8630 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008631 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008632 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008633 channels[i]->consumeMotionDown();
8634 }
8635 }
8636
8637 // Verify the order in which the events were received.
8638 EXPECT_EQ(3u, eventOrder.size());
8639 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8640 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8641 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8642}
8643
8644/**
8645 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8646 */
8647TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8648 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008649 auto spy = createSpy();
8650 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8652
8653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8656 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8657 spy->assertNoEvents();
8658}
8659
8660/**
8661 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8662 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8663 * to the window.
8664 */
8665TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8666 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008667 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008668 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8670
8671 // Inject an event outside the spy window's touchable region.
8672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8673 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8675 window->consumeMotionDown();
8676 spy->assertNoEvents();
8677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8678 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8679 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8680 window->consumeMotionUp();
8681 spy->assertNoEvents();
8682
8683 // Inject an event inside the spy window's touchable region.
8684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8685 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8686 {5, 10}))
8687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8688 window->consumeMotionDown();
8689 spy->consumeMotionDown();
8690}
8691
8692/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008693 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008694 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008695 */
8696TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8697 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008698 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008699 auto spy = createSpy();
8700 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008701 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008702 spy->setFrame(Rect{0, 0, 20, 20});
8703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8704
8705 // Inject an event outside the spy window's frame and touchable region.
8706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008707 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8708 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8710 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008711 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008712}
8713
8714/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008715 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8716 * pointers that are down within its bounds.
8717 */
8718TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8719 auto windowLeft = createForeground();
8720 windowLeft->setFrame({0, 0, 100, 200});
8721 auto windowRight = createForeground();
8722 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008723 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008724 spy->setFrame({0, 0, 200, 200});
8725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8726
8727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8729 {50, 50}))
8730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8731 windowLeft->consumeMotionDown();
8732 spy->consumeMotionDown();
8733
8734 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008735 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008736 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008737 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8738 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008739 .build();
8740 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8741 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8742 InputEventInjectionSync::WAIT_FOR_RESULT))
8743 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8744 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008745 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008746}
8747
8748/**
8749 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8750 * the spy should receive the second pointer with ACTION_DOWN.
8751 */
8752TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8753 auto window = createForeground();
8754 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008755 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008756 spyRight->setFrame({100, 0, 200, 200});
8757 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8758
8759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8760 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8761 {50, 50}))
8762 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8763 window->consumeMotionDown();
8764 spyRight->assertNoEvents();
8765
8766 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008767 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008768 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008769 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8770 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008771 .build();
8772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8773 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8774 InputEventInjectionSync::WAIT_FOR_RESULT))
8775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008776 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008777 spyRight->consumeMotionDown();
8778}
8779
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008780/**
8781 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8782 * windows should be allowed to control split touch.
8783 */
8784TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008785 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008786 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008787 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008788 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008789
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008790 auto window = createForeground();
8791 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008792
8793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8794
8795 // First finger down, no window touched.
8796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8797 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8798 {100, 200}))
8799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8800 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8801 window->assertNoEvents();
8802
8803 // Second finger down on window, the window should receive touch down.
8804 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008805 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008806 .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))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008810 .build();
8811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8812 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8813 InputEventInjectionSync::WAIT_FOR_RESULT))
8814 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8815
8816 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008817 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008818}
8819
8820/**
8821 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8822 * do not receive key events.
8823 */
8824TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008825 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008826 spy->setFocusable(false);
8827
8828 auto window = createForeground();
8829 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8830 setFocusedWindow(window);
8831 window->consumeFocusEvent(true);
8832
8833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8834 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8835 window->consumeKeyDown(ADISPLAY_ID_NONE);
8836
8837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8838 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8839 window->consumeKeyUp(ADISPLAY_ID_NONE);
8840
8841 spy->assertNoEvents();
8842}
8843
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008844using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8845
8846/**
8847 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8848 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8849 */
8850TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8851 auto window = createForeground();
8852 auto spy1 = createSpy();
8853 auto spy2 = createSpy();
8854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8855
8856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8857 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8858 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8859 window->consumeMotionDown();
8860 spy1->consumeMotionDown();
8861 spy2->consumeMotionDown();
8862
8863 // Pilfer pointers from the second spy window.
8864 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8865 spy2->assertNoEvents();
8866 spy1->consumeMotionCancel();
8867 window->consumeMotionCancel();
8868
8869 // The rest of the gesture should only be sent to the second spy window.
8870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8871 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8872 ADISPLAY_ID_DEFAULT))
8873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8874 spy2->consumeMotionMove();
8875 spy1->assertNoEvents();
8876 window->assertNoEvents();
8877}
8878
8879/**
8880 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8881 * in the middle of the gesture.
8882 */
8883TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8884 auto window = createForeground();
8885 auto spy = createSpy();
8886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8887
8888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8889 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8891 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8892 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8893
8894 window->releaseChannel();
8895
8896 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8897
8898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8899 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8901 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8902}
8903
8904/**
8905 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8906 * the spy, but not to any other windows.
8907 */
8908TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8909 auto spy = createSpy();
8910 auto window = createForeground();
8911
8912 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8913
8914 // First finger down on the window and the spy.
8915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8917 {100, 200}))
8918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8919 spy->consumeMotionDown();
8920 window->consumeMotionDown();
8921
8922 // Spy window pilfers the pointers.
8923 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8924 window->consumeMotionCancel();
8925
8926 // Second finger down on the window and spy, but the window should not receive the pointer down.
8927 const MotionEvent secondFingerDownEvent =
8928 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8929 .displayId(ADISPLAY_ID_DEFAULT)
8930 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008931 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8932 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008933 .build();
8934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8935 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8936 InputEventInjectionSync::WAIT_FOR_RESULT))
8937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8938
Harry Cutts33476232023-01-30 19:57:29 +00008939 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008940
8941 // Third finger goes down outside all windows, so injection should fail.
8942 const MotionEvent thirdFingerDownEvent =
8943 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8944 .displayId(ADISPLAY_ID_DEFAULT)
8945 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008946 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8947 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8948 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008949 .build();
8950 ASSERT_EQ(InputEventInjectionResult::FAILED,
8951 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8952 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008953 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008954
8955 spy->assertNoEvents();
8956 window->assertNoEvents();
8957}
8958
8959/**
8960 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8961 */
8962TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8963 auto spy = createSpy();
8964 spy->setFrame(Rect(0, 0, 100, 100));
8965 auto window = createForeground();
8966 window->setFrame(Rect(0, 0, 200, 200));
8967
8968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8969
8970 // First finger down on the window only
8971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8972 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8973 {150, 150}))
8974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8975 window->consumeMotionDown();
8976
8977 // Second finger down on the spy and window
8978 const MotionEvent secondFingerDownEvent =
8979 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8980 .displayId(ADISPLAY_ID_DEFAULT)
8981 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008982 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8983 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008984 .build();
8985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8986 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8987 InputEventInjectionSync::WAIT_FOR_RESULT))
8988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8989 spy->consumeMotionDown();
8990 window->consumeMotionPointerDown(1);
8991
8992 // Third finger down on the spy and window
8993 const MotionEvent thirdFingerDownEvent =
8994 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8995 .displayId(ADISPLAY_ID_DEFAULT)
8996 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008997 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8998 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8999 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009000 .build();
9001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9002 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
9003 InputEventInjectionSync::WAIT_FOR_RESULT))
9004 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9005 spy->consumeMotionPointerDown(1);
9006 window->consumeMotionPointerDown(2);
9007
9008 // Spy window pilfers the pointers.
9009 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9010 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9011 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9012
9013 spy->assertNoEvents();
9014 window->assertNoEvents();
9015}
9016
9017/**
9018 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
9019 * other windows should be canceled. If this results in the cancellation of all pointers for some
9020 * window, then that window should receive ACTION_CANCEL.
9021 */
9022TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
9023 auto spy = createSpy();
9024 spy->setFrame(Rect(0, 0, 100, 100));
9025 auto window = createForeground();
9026 window->setFrame(Rect(0, 0, 200, 200));
9027
9028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9029
9030 // First finger down on both spy and window
9031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9032 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9033 {10, 10}))
9034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9035 window->consumeMotionDown();
9036 spy->consumeMotionDown();
9037
9038 // Second finger down on the spy and window
9039 const MotionEvent secondFingerDownEvent =
9040 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9041 .displayId(ADISPLAY_ID_DEFAULT)
9042 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009043 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9044 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009045 .build();
9046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9047 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9048 InputEventInjectionSync::WAIT_FOR_RESULT))
9049 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9050 spy->consumeMotionPointerDown(1);
9051 window->consumeMotionPointerDown(1);
9052
9053 // Spy window pilfers the pointers.
9054 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9055 window->consumeMotionCancel();
9056
9057 spy->assertNoEvents();
9058 window->assertNoEvents();
9059}
9060
9061/**
9062 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
9063 * be sent to other windows
9064 */
9065TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
9066 auto spy = createSpy();
9067 spy->setFrame(Rect(0, 0, 100, 100));
9068 auto window = createForeground();
9069 window->setFrame(Rect(0, 0, 200, 200));
9070
9071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9072
9073 // First finger down on both window and spy
9074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9076 {10, 10}))
9077 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9078 window->consumeMotionDown();
9079 spy->consumeMotionDown();
9080
9081 // Spy window pilfers the pointers.
9082 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9083 window->consumeMotionCancel();
9084
9085 // Second finger down on the window only
9086 const MotionEvent secondFingerDownEvent =
9087 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9088 .displayId(ADISPLAY_ID_DEFAULT)
9089 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009090 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9091 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009092 .build();
9093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9094 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9095 InputEventInjectionSync::WAIT_FOR_RESULT))
9096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9097 window->consumeMotionDown();
9098 window->assertNoEvents();
9099
9100 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
9101 spy->consumeMotionMove();
9102 spy->assertNoEvents();
9103}
9104
Prabir Pradhand65552b2021-10-07 11:23:50 -07009105class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
9106public:
9107 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
9108 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9109 std::make_shared<FakeApplicationHandle>();
9110 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009111 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
9112 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009113 overlay->setFocusable(false);
9114 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08009115 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009116 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009117 overlay->setTrustedOverlay(true);
9118
9119 std::shared_ptr<FakeApplicationHandle> application =
9120 std::make_shared<FakeApplicationHandle>();
9121 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009122 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9123 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009124 window->setFocusable(true);
9125 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009126
9127 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9129 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009130 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009131 return {std::move(overlay), std::move(window)};
9132 }
9133
9134 void sendFingerEvent(int32_t action) {
9135 NotifyMotionArgs motionArgs =
9136 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9137 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9138 mDispatcher->notifyMotion(&motionArgs);
9139 }
9140
9141 void sendStylusEvent(int32_t action) {
9142 NotifyMotionArgs motionArgs =
9143 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9144 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9145 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9146 mDispatcher->notifyMotion(&motionArgs);
9147 }
9148};
9149
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009150using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9151
9152TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9153 ScopedSilentDeath _silentDeath;
9154
Prabir Pradhand65552b2021-10-07 11:23:50 -07009155 auto [overlay, window] = setupStylusOverlayScenario();
9156 overlay->setTrustedOverlay(false);
9157 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9158 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9159 ".* not a trusted overlay");
9160}
9161
9162TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9163 auto [overlay, window] = setupStylusOverlayScenario();
9164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9165
9166 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9167 overlay->consumeMotionDown();
9168 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9169 overlay->consumeMotionUp();
9170
9171 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9172 window->consumeMotionDown();
9173 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9174 window->consumeMotionUp();
9175
9176 overlay->assertNoEvents();
9177 window->assertNoEvents();
9178}
9179
9180TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9181 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009182 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9184
9185 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9186 overlay->consumeMotionDown();
9187 window->consumeMotionDown();
9188 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9189 overlay->consumeMotionUp();
9190 window->consumeMotionUp();
9191
9192 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9193 window->consumeMotionDown();
9194 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9195 window->consumeMotionUp();
9196
9197 overlay->assertNoEvents();
9198 window->assertNoEvents();
9199}
9200
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009201/**
9202 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9203 * The scenario is as follows:
9204 * - The stylus interceptor overlay is configured as a spy window.
9205 * - The stylus interceptor spy receives the start of a new stylus gesture.
9206 * - It pilfers pointers and then configures itself to no longer be a spy.
9207 * - The stylus interceptor continues to receive the rest of the gesture.
9208 */
9209TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9210 auto [overlay, window] = setupStylusOverlayScenario();
9211 overlay->setSpy(true);
9212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9213
9214 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9215 overlay->consumeMotionDown();
9216 window->consumeMotionDown();
9217
9218 // The interceptor pilfers the pointers.
9219 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9220 window->consumeMotionCancel();
9221
9222 // The interceptor configures itself so that it is no longer a spy.
9223 overlay->setSpy(false);
9224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9225
9226 // It continues to receive the rest of the stylus gesture.
9227 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9228 overlay->consumeMotionMove();
9229 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9230 overlay->consumeMotionUp();
9231
9232 window->assertNoEvents();
9233}
9234
Prabir Pradhan5735a322022-04-11 17:23:34 +00009235struct User {
9236 int32_t mPid;
9237 int32_t mUid;
9238 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9239 std::unique_ptr<InputDispatcher>& mDispatcher;
9240
9241 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9242 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9243
9244 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9245 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9246 ADISPLAY_ID_DEFAULT, {100, 200},
9247 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9248 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9249 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9250 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9251 }
9252
9253 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009254 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009255 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009256 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009257 mPolicyFlags);
9258 }
9259
9260 sp<FakeWindowHandle> createWindow() const {
9261 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9262 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009263 sp<FakeWindowHandle> window =
9264 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9265 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009266 window->setOwnerInfo(mPid, mUid);
9267 return window;
9268 }
9269};
9270
9271using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9272
9273TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9274 auto owner = User(mDispatcher, 10, 11);
9275 auto window = owner.createWindow();
9276 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9277
9278 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9279 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9280 window->consumeMotionDown();
9281
9282 setFocusedWindow(window);
9283 window->consumeFocusEvent(true);
9284
9285 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9286 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9287 window->consumeKeyDown(ADISPLAY_ID_NONE);
9288}
9289
9290TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9291 auto owner = User(mDispatcher, 10, 11);
9292 auto window = owner.createWindow();
9293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9294
9295 auto rando = User(mDispatcher, 20, 21);
9296 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9297 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9298
9299 setFocusedWindow(window);
9300 window->consumeFocusEvent(true);
9301
9302 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9303 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9304 window->assertNoEvents();
9305}
9306
9307TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9308 auto owner = User(mDispatcher, 10, 11);
9309 auto window = owner.createWindow();
9310 auto spy = owner.createWindow();
9311 spy->setSpy(true);
9312 spy->setTrustedOverlay(true);
9313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9314
9315 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9316 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9317 spy->consumeMotionDown();
9318 window->consumeMotionDown();
9319}
9320
9321TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9322 auto owner = User(mDispatcher, 10, 11);
9323 auto window = owner.createWindow();
9324
9325 auto rando = User(mDispatcher, 20, 21);
9326 auto randosSpy = rando.createWindow();
9327 randosSpy->setSpy(true);
9328 randosSpy->setTrustedOverlay(true);
9329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9330
9331 // The event is targeted at owner's window, so injection should succeed, but the spy should
9332 // not receive the event.
9333 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9334 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9335 randosSpy->assertNoEvents();
9336 window->consumeMotionDown();
9337}
9338
9339TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9340 auto owner = User(mDispatcher, 10, 11);
9341 auto window = owner.createWindow();
9342
9343 auto rando = User(mDispatcher, 20, 21);
9344 auto randosSpy = rando.createWindow();
9345 randosSpy->setSpy(true);
9346 randosSpy->setTrustedOverlay(true);
9347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9348
9349 // A user that has injection permission can inject into any window.
9350 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9351 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9352 ADISPLAY_ID_DEFAULT));
9353 randosSpy->consumeMotionDown();
9354 window->consumeMotionDown();
9355
9356 setFocusedWindow(randosSpy);
9357 randosSpy->consumeFocusEvent(true);
9358
9359 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9360 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9361 window->assertNoEvents();
9362}
9363
9364TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9365 auto owner = User(mDispatcher, 10, 11);
9366 auto window = owner.createWindow();
9367
9368 auto rando = User(mDispatcher, 20, 21);
9369 auto randosWindow = rando.createWindow();
9370 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9371 randosWindow->setWatchOutsideTouch(true);
9372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9373
9374 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9375 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9376 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9377 window->consumeMotionDown();
9378 randosWindow->consumeMotionOutside();
9379}
9380
Garfield Tane84e6f92019-08-29 17:28:41 -07009381} // namespace android::inputdispatcher