blob: fb808eb2a3c16da3f297a3f86671454d1625fc0e [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
Chavi Weingarten847e8512023-03-29 00:26:09 +0000640 void setFocusedWindow(const sp<WindowInfoHandle>& window) {
Vishnu Nair958da932020-08-21 17:12:37 -0700641 FocusRequest request;
642 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000643 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700644 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
645 request.displayId = window->getInfo()->displayId;
646 mDispatcher->setFocusedWindow(request);
647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648};
649
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
651 KeyEvent event;
652
653 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800654 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
655 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600656 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
657 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800658 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000659 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000660 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 << "Should reject key events with undefined action.";
662
663 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800664 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
665 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600666 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800667 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000668 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000669 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 << "Should reject key events with ACTION_MULTIPLE.";
671}
672
673TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
674 MotionEvent event;
675 PointerProperties pointerProperties[MAX_POINTERS + 1];
676 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800677 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 pointerProperties[i].clear();
679 pointerProperties[i].id = i;
680 pointerCoords[i].clear();
681 }
682
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800683 // Some constants commonly used below
684 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
685 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
686 constexpr int32_t metaState = AMETA_NONE;
687 constexpr MotionClassification classification = MotionClassification::NONE;
688
chaviw9eaa22c2020-07-01 16:21:27 -0700689 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800691 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700692 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
693 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700694 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
695 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700696 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800697 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000698 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000699 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 << "Should reject motion events with undefined action.";
701
702 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800703 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800704 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
705 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
706 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
707 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500708 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800709 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000710 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000711 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 << "Should reject motion events with pointer down index too large.";
713
Garfield Tanfbe732e2020-01-24 11:26:14 -0800714 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700715 AMOTION_EVENT_ACTION_POINTER_DOWN |
716 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700717 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
718 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700719 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500720 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800721 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000722 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000723 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 << "Should reject motion events with pointer down index too small.";
725
726 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800727 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800728 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
729 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
730 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
731 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500732 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800733 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000734 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000735 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 << "Should reject motion events with pointer up index too large.";
737
Garfield Tanfbe732e2020-01-24 11:26:14 -0800738 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700739 AMOTION_EVENT_ACTION_POINTER_UP |
740 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700741 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
742 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700743 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500744 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800745 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000746 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000747 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 << "Should reject motion events with pointer up index too small.";
749
750 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800751 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
752 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700753 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700754 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
755 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700756 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800757 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000758 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000759 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 << "Should reject motion events with 0 pointers.";
761
Garfield Tanfbe732e2020-01-24 11:26:14 -0800762 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
763 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700764 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700765 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
766 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800768 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000769 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000770 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 << "Should reject motion events with more than MAX_POINTERS pointers.";
772
773 // Rejects motion events with invalid pointer ids.
774 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800775 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
776 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700777 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700778 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
779 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700780 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800781 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000782 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000783 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 << "Should reject motion events with pointer ids less than 0.";
785
786 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800787 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
788 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700789 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700790 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
791 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700792 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800793 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000794 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000795 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
797
798 // Rejects motion events with duplicate pointer ids.
799 pointerProperties[0].id = 1;
800 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800801 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
802 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700803 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700804 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
805 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700806 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800807 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000808 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000809 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 << "Should reject motion events with duplicate pointer ids.";
811}
812
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800813/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
814
815TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
816 constexpr nsecs_t eventTime = 20;
Harry Cutts33476232023-01-30 19:57:29 +0000817 NotifyConfigurationChangedArgs args(/*id=*/10, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800818 mDispatcher->notifyConfigurationChanged(&args);
819 ASSERT_TRUE(mDispatcher->waitForIdle());
820
821 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
822}
823
824TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Harry Cutts33476232023-01-30 19:57:29 +0000825 NotifySwitchArgs args(/*id=*/10, /*eventTime=*/20, /*policyFlags=*/0, /*switchValues=*/1,
826 /*switchMask=*/2);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800827 mDispatcher->notifySwitch(&args);
828
829 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
830 args.policyFlags |= POLICY_FLAG_TRUSTED;
831 mFakePolicy->assertNotifySwitchWasCalled(args);
832}
833
Arthur Hungb92218b2018-08-14 12:00:21 +0800834// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700835static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700836// Default input dispatching timeout if there is no focused application or paused window
837// from which to determine an appropriate dispatching timeout.
838static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
839 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
840 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800841
842class FakeApplicationHandle : public InputApplicationHandle {
843public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700844 FakeApplicationHandle() {
845 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700846 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500847 mInfo.dispatchingTimeoutMillis =
848 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700849 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800850 virtual ~FakeApplicationHandle() {}
851
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000852 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700853
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500854 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
855 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700856 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800857};
858
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800859class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800860public:
Garfield Tan15601662020-09-22 15:32:38 -0700861 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800862 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700863 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800864 }
865
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800866 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700867 InputEvent* event;
868 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
869 if (!consumeSeq) {
870 return nullptr;
871 }
872 finishEvent(*consumeSeq);
873 return event;
874 }
875
876 /**
877 * Receive an event without acknowledging it.
878 * Return the sequence number that could later be used to send finished signal.
879 */
880 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800881 uint32_t consumeSeq;
882 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800883
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800884 std::chrono::time_point start = std::chrono::steady_clock::now();
885 status_t status = WOULD_BLOCK;
886 while (status == WOULD_BLOCK) {
Harry Cutts33476232023-01-30 19:57:29 +0000887 status = mConsumer->consume(&mEventFactory, /*consumeBatches=*/true, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800888 &event);
889 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
890 if (elapsed > 100ms) {
891 break;
892 }
893 }
894
895 if (status == WOULD_BLOCK) {
896 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700897 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800898 }
899
900 if (status != OK) {
901 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700902 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800903 }
904 if (event == nullptr) {
905 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700906 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800907 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700908 if (outEvent != nullptr) {
909 *outEvent = event;
910 }
911 return consumeSeq;
912 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800913
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700914 /**
915 * To be used together with "receiveEvent" to complete the consumption of an event.
916 */
917 void finishEvent(uint32_t consumeSeq) {
918 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
919 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800920 }
921
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000922 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
923 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
924 ASSERT_EQ(OK, status);
925 }
926
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000927 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
928 std::optional<int32_t> expectedDisplayId,
929 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800930 InputEvent* event = consume();
931
932 ASSERT_NE(nullptr, event) << mName.c_str()
933 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800934 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800936 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800937
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000938 if (expectedDisplayId.has_value()) {
939 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
940 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800941
Tiger Huang8664f8c2018-10-11 19:14:35 +0800942 switch (expectedEventType) {
943 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800944 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
945 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000946 if (expectedFlags.has_value()) {
947 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
948 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800949 break;
950 }
951 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800952 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000953 assertMotionAction(expectedAction, motionEvent.getAction());
954
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000955 if (expectedFlags.has_value()) {
956 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
957 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800958 break;
959 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100960 case AINPUT_EVENT_TYPE_FOCUS: {
961 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
962 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800963 case AINPUT_EVENT_TYPE_CAPTURE: {
964 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
965 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000966 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
967 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
968 }
arthurhungb89ccb02020-12-30 16:19:01 +0800969 case AINPUT_EVENT_TYPE_DRAG: {
970 FAIL() << "Use 'consumeDragEvent' for DRAG events";
971 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800972 default: {
973 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
974 }
975 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800976 }
977
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800978 MotionEvent* consumeMotion() {
979 InputEvent* event = consume();
980
981 if (event == nullptr) {
982 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
983 return nullptr;
984 }
985
986 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
987 ADD_FAILURE() << mName << " expected a MotionEvent, got "
988 << inputEventTypeToString(event->getType()) << " event";
989 return nullptr;
990 }
991 return static_cast<MotionEvent*>(event);
992 }
993
994 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
995 MotionEvent* motionEvent = consumeMotion();
996 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
997 ASSERT_THAT(*motionEvent, matcher);
998 }
999
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001000 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
1001 InputEvent* event = consume();
1002 ASSERT_NE(nullptr, event) << mName.c_str()
1003 << ": consumer should have returned non-NULL event.";
1004 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
1005 << "Got " << inputEventTypeToString(event->getType())
1006 << " event instead of FOCUS event";
1007
1008 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1009 << mName.c_str() << ": event displayId should always be NONE.";
1010
1011 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
1012 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001013 }
1014
Prabir Pradhan99987712020-11-10 18:43:05 -08001015 void consumeCaptureEvent(bool hasCapture) {
1016 const InputEvent* event = consume();
1017 ASSERT_NE(nullptr, event) << mName.c_str()
1018 << ": consumer should have returned non-NULL event.";
1019 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
1020 << "Got " << inputEventTypeToString(event->getType())
1021 << " event instead of CAPTURE event";
1022
1023 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1024 << mName.c_str() << ": event displayId should always be NONE.";
1025
1026 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1027 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1028 }
1029
arthurhungb89ccb02020-12-30 16:19:01 +08001030 void consumeDragEvent(bool isExiting, float x, float y) {
1031 const InputEvent* event = consume();
1032 ASSERT_NE(nullptr, event) << mName.c_str()
1033 << ": consumer should have returned non-NULL event.";
1034 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1035 << "Got " << inputEventTypeToString(event->getType())
1036 << " event instead of DRAG event";
1037
1038 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1039 << mName.c_str() << ": event displayId should always be NONE.";
1040
1041 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1042 EXPECT_EQ(isExiting, dragEvent.isExiting());
1043 EXPECT_EQ(x, dragEvent.getX());
1044 EXPECT_EQ(y, dragEvent.getY());
1045 }
1046
Antonio Kantekf16f2832021-09-28 04:39:20 +00001047 void consumeTouchModeEvent(bool inTouchMode) {
1048 const InputEvent* event = consume();
1049 ASSERT_NE(nullptr, event) << mName.c_str()
1050 << ": consumer should have returned non-NULL event.";
1051 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1052 << "Got " << inputEventTypeToString(event->getType())
1053 << " event instead of TOUCH_MODE event";
1054
1055 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1056 << mName.c_str() << ": event displayId should always be NONE.";
1057 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1058 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1059 }
1060
chaviwd1c23182019-12-20 18:44:56 -08001061 void assertNoEvents() {
1062 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001063 if (event == nullptr) {
1064 return;
1065 }
1066 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1067 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1068 ADD_FAILURE() << "Received key event "
1069 << KeyEvent::actionToString(keyEvent.getAction());
1070 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1071 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1072 ADD_FAILURE() << "Received motion event "
1073 << MotionEvent::actionToString(motionEvent.getAction());
1074 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1075 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1076 ADD_FAILURE() << "Received focus event, hasFocus = "
1077 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001078 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1079 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1080 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1081 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001082 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1083 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1084 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1085 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001086 }
1087 FAIL() << mName.c_str()
1088 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001089 }
1090
1091 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1092
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001093 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1094
chaviwd1c23182019-12-20 18:44:56 -08001095protected:
1096 std::unique_ptr<InputConsumer> mConsumer;
1097 PreallocatedInputEventFactory mEventFactory;
1098
1099 std::string mName;
1100};
1101
chaviw3277faf2021-05-19 16:45:23 -05001102class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001103public:
1104 static const int32_t WIDTH = 600;
1105 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001106
Chris Yea209fde2020-07-22 13:54:51 -07001107 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001108 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001109 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001110 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001111 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001112 base::Result<std::unique_ptr<InputChannel>> channel =
1113 dispatcher->createInputChannel(name);
1114 token = (*channel)->getConnectionToken();
1115 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001116 }
1117
1118 inputApplicationHandle->updateInfo();
1119 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1120
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001121 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001122 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001123 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001124 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001125 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001126 mInfo.frameLeft = 0;
1127 mInfo.frameTop = 0;
1128 mInfo.frameRight = WIDTH;
1129 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001130 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001131 mInfo.globalScaleFactor = 1.0;
1132 mInfo.touchableRegion.clear();
1133 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001134 mInfo.ownerPid = WINDOW_PID;
1135 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001136 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001137 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001138 }
1139
Arthur Hungabbb9d82021-09-01 14:52:30 +00001140 sp<FakeWindowHandle> clone(
1141 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001142 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001143 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001144 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1145 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001146 return handle;
1147 }
1148
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001149 void setTouchable(bool touchable) {
1150 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1151 }
chaviwd1c23182019-12-20 18:44:56 -08001152
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001153 void setFocusable(bool focusable) {
1154 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1155 }
1156
1157 void setVisible(bool visible) {
1158 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1159 }
Vishnu Nair958da932020-08-21 17:12:37 -07001160
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001161 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001162 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001163 }
1164
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001165 void setPaused(bool paused) {
1166 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1167 }
1168
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001169 void setPreventSplitting(bool preventSplitting) {
1170 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001171 }
1172
1173 void setSlippery(bool slippery) {
1174 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1175 }
1176
1177 void setWatchOutsideTouch(bool watchOutside) {
1178 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1179 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001180
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001181 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1182
1183 void setInterceptsStylus(bool interceptsStylus) {
1184 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1185 }
1186
1187 void setDropInput(bool dropInput) {
1188 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1189 }
1190
1191 void setDropInputIfObscured(bool dropInputIfObscured) {
1192 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1193 }
1194
1195 void setNoInputChannel(bool noInputChannel) {
1196 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1197 }
1198
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001199 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1200
chaviw3277faf2021-05-19 16:45:23 -05001201 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001202
Bernardo Rufino7393d172021-02-26 13:56:11 +00001203 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1204
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001205 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001206 mInfo.frameLeft = frame.left;
1207 mInfo.frameTop = frame.top;
1208 mInfo.frameRight = frame.right;
1209 mInfo.frameBottom = frame.bottom;
1210 mInfo.touchableRegion.clear();
1211 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001212
1213 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1214 ui::Transform translate;
1215 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1216 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001217 }
1218
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001219 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1220
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001221 void setIsWallpaper(bool isWallpaper) {
1222 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1223 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001224
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001225 void setDupTouchToWallpaper(bool hasWallpaper) {
1226 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1227 }
chaviwd1c23182019-12-20 18:44:56 -08001228
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001229 void setTrustedOverlay(bool trustedOverlay) {
1230 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1231 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001232
chaviw9eaa22c2020-07-01 16:21:27 -07001233 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1234 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1235 }
1236
1237 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001238
yunho.shinf4a80b82020-11-16 21:13:57 +09001239 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1240
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001241 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1242 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1243 expectedFlags);
1244 }
1245
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001246 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1247 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1248 }
1249
Svet Ganov5d3bc372020-01-26 23:11:07 -08001250 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001251 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001252 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1253 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001254 }
1255
1256 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001257 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001258 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1259 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001260 }
1261
1262 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001263 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001264 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1265 }
1266
1267 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1268 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001269 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1270 expectedFlags);
1271 }
1272
Svet Ganov5d3bc372020-01-26 23:11:07 -08001273 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001274 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1275 int32_t expectedFlags = 0) {
1276 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1277 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001278 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1279 }
1280
1281 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001282 int32_t expectedFlags = 0) {
1283 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1284 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001285 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1286 }
1287
1288 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001289 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001290 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1291 expectedFlags);
1292 }
1293
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001294 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1295 int32_t expectedFlags = 0) {
1296 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1297 expectedFlags);
1298 }
1299
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001300 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1301 int32_t expectedFlags = 0) {
1302 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001303 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001304 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1305 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1306 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1307 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1308 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1309 }
1310
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001311 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1312 ASSERT_NE(mInputReceiver, nullptr)
1313 << "Cannot consume events from a window with no receiver";
1314 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1315 }
1316
Prabir Pradhan99987712020-11-10 18:43:05 -08001317 void consumeCaptureEvent(bool hasCapture) {
1318 ASSERT_NE(mInputReceiver, nullptr)
1319 << "Cannot consume events from a window with no receiver";
1320 mInputReceiver->consumeCaptureEvent(hasCapture);
1321 }
1322
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001323 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1324 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001325 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001326 ASSERT_THAT(*motionEvent, matcher);
1327 }
1328
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001329 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1330 std::optional<int32_t> expectedDisplayId,
1331 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001332 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1333 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1334 expectedFlags);
1335 }
1336
arthurhungb89ccb02020-12-30 16:19:01 +08001337 void consumeDragEvent(bool isExiting, float x, float y) {
1338 mInputReceiver->consumeDragEvent(isExiting, x, y);
1339 }
1340
Antonio Kantekf16f2832021-09-28 04:39:20 +00001341 void consumeTouchModeEvent(bool inTouchMode) {
1342 ASSERT_NE(mInputReceiver, nullptr)
1343 << "Cannot consume events from a window with no receiver";
1344 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1345 }
1346
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001347 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001348 if (mInputReceiver == nullptr) {
1349 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1350 return std::nullopt;
1351 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001352 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001353 }
1354
1355 void finishEvent(uint32_t sequenceNum) {
1356 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1357 mInputReceiver->finishEvent(sequenceNum);
1358 }
1359
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001360 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1361 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1362 mInputReceiver->sendTimeline(inputEventId, timeline);
1363 }
1364
chaviwaf87b3e2019-10-01 16:59:28 -07001365 InputEvent* consume() {
1366 if (mInputReceiver == nullptr) {
1367 return nullptr;
1368 }
1369 return mInputReceiver->consume();
1370 }
1371
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001372 MotionEvent* consumeMotion() {
1373 InputEvent* event = consume();
1374 if (event == nullptr) {
1375 ADD_FAILURE() << "Consume failed : no event";
1376 return nullptr;
1377 }
1378 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1379 ADD_FAILURE() << "Instead of motion event, got "
1380 << inputEventTypeToString(event->getType());
1381 return nullptr;
1382 }
1383 return static_cast<MotionEvent*>(event);
1384 }
1385
Arthur Hungb92218b2018-08-14 12:00:21 +08001386 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001387 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001388 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001389 return; // Can't receive events if the window does not have input channel
1390 }
1391 ASSERT_NE(nullptr, mInputReceiver)
1392 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001393 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001394 }
1395
chaviwaf87b3e2019-10-01 16:59:28 -07001396 sp<IBinder> getToken() { return mInfo.token; }
1397
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001398 const std::string& getName() { return mName; }
1399
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001400 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1401 mInfo.ownerPid = ownerPid;
1402 mInfo.ownerUid = ownerUid;
1403 }
1404
Prabir Pradhanedd96402022-02-15 01:46:16 -08001405 int32_t getPid() const { return mInfo.ownerPid; }
1406
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001407 void destroyReceiver() { mInputReceiver = nullptr; }
1408
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001409 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1410
chaviwd1c23182019-12-20 18:44:56 -08001411private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001412 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001413 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001414 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001415};
1416
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001417std::atomic<int32_t> FakeWindowHandle::sId{1};
1418
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001419static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001420 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 int32_t displayId = ADISPLAY_ID_NONE,
1422 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001423 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001424 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1425 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001426 KeyEvent event;
1427 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1428
1429 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001430 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Harry Cutts33476232023-01-30 19:57:29 +00001431 INVALID_HMAC, action, /*flags=*/0, AKEYCODE_A, KEY_A, AMETA_NONE, repeatCount,
1432 currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001433
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001434 if (!allowKeyRepeat) {
1435 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1436 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001437 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001438 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001439}
1440
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001441static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001442 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001443 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001444}
1445
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001446// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1447// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1448// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001449static InputEventInjectionResult injectKeyDownNoRepeat(
1450 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001451 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001452 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
Harry Cutts33476232023-01-30 19:57:29 +00001453 /*allowKeyRepeat=*/false);
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001454}
1455
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001456static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001457 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001458 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /*repeatCount=*/0, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001459}
1460
Garfield Tandf26e862020-07-01 20:18:19 -07001461class PointerBuilder {
1462public:
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001463 PointerBuilder(int32_t id, ToolType toolType) {
Garfield Tandf26e862020-07-01 20:18:19 -07001464 mProperties.clear();
1465 mProperties.id = id;
1466 mProperties.toolType = toolType;
1467 mCoords.clear();
1468 }
1469
1470 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1471
1472 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1473
1474 PointerBuilder& axis(int32_t axis, float value) {
1475 mCoords.setAxisValue(axis, value);
1476 return *this;
1477 }
1478
1479 PointerProperties buildProperties() const { return mProperties; }
1480
1481 PointerCoords buildCoords() const { return mCoords; }
1482
1483private:
1484 PointerProperties mProperties;
1485 PointerCoords mCoords;
1486};
1487
1488class MotionEventBuilder {
1489public:
1490 MotionEventBuilder(int32_t action, int32_t source) {
1491 mAction = action;
1492 mSource = source;
1493 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001494 mDownTime = mEventTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001495 }
1496
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001497 MotionEventBuilder& deviceId(int32_t deviceId) {
1498 mDeviceId = deviceId;
1499 return *this;
1500 }
1501
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001502 MotionEventBuilder& downTime(nsecs_t downTime) {
1503 mDownTime = downTime;
1504 return *this;
1505 }
1506
Garfield Tandf26e862020-07-01 20:18:19 -07001507 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1508 mEventTime = eventTime;
1509 return *this;
1510 }
1511
1512 MotionEventBuilder& displayId(int32_t displayId) {
1513 mDisplayId = displayId;
1514 return *this;
1515 }
1516
1517 MotionEventBuilder& actionButton(int32_t actionButton) {
1518 mActionButton = actionButton;
1519 return *this;
1520 }
1521
arthurhung6d4bed92021-03-17 11:59:33 +08001522 MotionEventBuilder& buttonState(int32_t buttonState) {
1523 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001524 return *this;
1525 }
1526
1527 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1528 mRawXCursorPosition = rawXCursorPosition;
1529 return *this;
1530 }
1531
1532 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1533 mRawYCursorPosition = rawYCursorPosition;
1534 return *this;
1535 }
1536
1537 MotionEventBuilder& pointer(PointerBuilder pointer) {
1538 mPointers.push_back(pointer);
1539 return *this;
1540 }
1541
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001542 MotionEventBuilder& addFlag(uint32_t flags) {
1543 mFlags |= flags;
1544 return *this;
1545 }
1546
Garfield Tandf26e862020-07-01 20:18:19 -07001547 MotionEvent build() {
1548 std::vector<PointerProperties> pointerProperties;
1549 std::vector<PointerCoords> pointerCoords;
1550 for (const PointerBuilder& pointer : mPointers) {
1551 pointerProperties.push_back(pointer.buildProperties());
1552 pointerCoords.push_back(pointer.buildCoords());
1553 }
1554
1555 // Set mouse cursor position for the most common cases to avoid boilerplate.
1556 if (mSource == AINPUT_SOURCE_MOUSE &&
1557 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1558 mPointers.size() == 1) {
1559 mRawXCursorPosition = pointerCoords[0].getX();
1560 mRawYCursorPosition = pointerCoords[0].getY();
1561 }
1562
1563 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001564 ui::Transform identityTransform;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001565 event.initialize(InputEvent::nextId(), mDeviceId, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001566 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001567 mButtonState, MotionClassification::NONE, identityTransform,
1568 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001569 mRawYCursorPosition, identityTransform, mDownTime, mEventTime,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001570 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001571
1572 return event;
1573 }
1574
1575private:
1576 int32_t mAction;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001577 int32_t mDeviceId = DEVICE_ID;
Garfield Tandf26e862020-07-01 20:18:19 -07001578 int32_t mSource;
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001579 nsecs_t mDownTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001580 nsecs_t mEventTime;
1581 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1582 int32_t mActionButton{0};
1583 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001584 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001585 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1586 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1587
1588 std::vector<PointerBuilder> mPointers;
1589};
1590
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08001591class MotionArgsBuilder {
1592public:
1593 MotionArgsBuilder(int32_t action, int32_t source) {
1594 mAction = action;
1595 mSource = source;
1596 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1597 mDownTime = mEventTime;
1598 }
1599
1600 MotionArgsBuilder& deviceId(int32_t deviceId) {
1601 mDeviceId = deviceId;
1602 return *this;
1603 }
1604
1605 MotionArgsBuilder& downTime(nsecs_t downTime) {
1606 mDownTime = downTime;
1607 return *this;
1608 }
1609
1610 MotionArgsBuilder& eventTime(nsecs_t eventTime) {
1611 mEventTime = eventTime;
1612 return *this;
1613 }
1614
1615 MotionArgsBuilder& displayId(int32_t displayId) {
1616 mDisplayId = displayId;
1617 return *this;
1618 }
1619
1620 MotionArgsBuilder& policyFlags(int32_t policyFlags) {
1621 mPolicyFlags = policyFlags;
1622 return *this;
1623 }
1624
1625 MotionArgsBuilder& actionButton(int32_t actionButton) {
1626 mActionButton = actionButton;
1627 return *this;
1628 }
1629
1630 MotionArgsBuilder& buttonState(int32_t buttonState) {
1631 mButtonState = buttonState;
1632 return *this;
1633 }
1634
1635 MotionArgsBuilder& rawXCursorPosition(float rawXCursorPosition) {
1636 mRawXCursorPosition = rawXCursorPosition;
1637 return *this;
1638 }
1639
1640 MotionArgsBuilder& rawYCursorPosition(float rawYCursorPosition) {
1641 mRawYCursorPosition = rawYCursorPosition;
1642 return *this;
1643 }
1644
1645 MotionArgsBuilder& pointer(PointerBuilder pointer) {
1646 mPointers.push_back(pointer);
1647 return *this;
1648 }
1649
1650 MotionArgsBuilder& addFlag(uint32_t flags) {
1651 mFlags |= flags;
1652 return *this;
1653 }
1654
1655 NotifyMotionArgs build() {
1656 std::vector<PointerProperties> pointerProperties;
1657 std::vector<PointerCoords> pointerCoords;
1658 for (const PointerBuilder& pointer : mPointers) {
1659 pointerProperties.push_back(pointer.buildProperties());
1660 pointerCoords.push_back(pointer.buildCoords());
1661 }
1662
1663 // Set mouse cursor position for the most common cases to avoid boilerplate.
1664 if (mSource == AINPUT_SOURCE_MOUSE &&
1665 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1666 mPointers.size() == 1) {
1667 mRawXCursorPosition = pointerCoords[0].getX();
1668 mRawYCursorPosition = pointerCoords[0].getY();
1669 }
1670
1671 NotifyMotionArgs args(InputEvent::nextId(), mEventTime, /*readTime=*/mEventTime, mDeviceId,
1672 mSource, mDisplayId, mPolicyFlags, mAction, mActionButton, mFlags,
1673 AMETA_NONE, mButtonState, MotionClassification::NONE, /*edgeFlags=*/0,
1674 mPointers.size(), pointerProperties.data(), pointerCoords.data(),
1675 /*xPrecision=*/0, /*yPrecision=*/0, mRawXCursorPosition,
1676 mRawYCursorPosition, mDownTime, /*videoFrames=*/{});
1677
1678 return args;
1679 }
1680
1681private:
1682 int32_t mAction;
1683 int32_t mDeviceId = DEVICE_ID;
1684 int32_t mSource;
1685 nsecs_t mDownTime;
1686 nsecs_t mEventTime;
1687 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1688 int32_t mPolicyFlags = DEFAULT_POLICY_FLAGS;
1689 int32_t mActionButton{0};
1690 int32_t mButtonState{0};
1691 int32_t mFlags{0};
1692 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1693 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1694
1695 std::vector<PointerBuilder> mPointers;
1696};
1697
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001698static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001699 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001700 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001701 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1702 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1703 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1704 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001705}
1706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001707static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001708 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001709 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001710 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001711 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1712 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001713 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001714 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1715 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001716 MotionEvent event = MotionEventBuilder(action, source)
1717 .displayId(displayId)
1718 .eventTime(eventTime)
1719 .rawXCursorPosition(cursorPosition.x)
1720 .rawYCursorPosition(cursorPosition.y)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001721 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001722 .x(position.x)
1723 .y(position.y))
1724 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001725
1726 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001727 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1728 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001729}
1730
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001731static InputEventInjectionResult injectMotionDown(
1732 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1733 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001734 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001735}
1736
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001737static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001738 int32_t source, int32_t displayId,
1739 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001740 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001741}
1742
Jackal Guof9696682018-10-05 12:23:23 +08001743static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1744 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1745 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001746 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001747 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1748 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001749
1750 return args;
1751}
1752
chaviwd1c23182019-12-20 18:44:56 -08001753static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1754 const std::vector<PointF>& points) {
1755 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001756 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1757 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1758 }
1759
chaviwd1c23182019-12-20 18:44:56 -08001760 PointerProperties pointerProperties[pointerCount];
1761 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001762
chaviwd1c23182019-12-20 18:44:56 -08001763 for (size_t i = 0; i < pointerCount; i++) {
1764 pointerProperties[i].clear();
1765 pointerProperties[i].id = i;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001766 pointerProperties[i].toolType = ToolType::FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001767
chaviwd1c23182019-12-20 18:44:56 -08001768 pointerCoords[i].clear();
1769 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1770 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1771 }
Jackal Guof9696682018-10-05 12:23:23 +08001772
1773 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1774 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001775 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001776 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1777 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001778 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1779 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001780 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1781 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001782
1783 return args;
1784}
1785
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001786static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1787 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1788}
1789
chaviwd1c23182019-12-20 18:44:56 -08001790static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1791 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1792}
1793
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001794static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1795 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001796 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001797}
1798
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001799/**
1800 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1801 * broken channel.
1802 */
1803TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1804 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1805 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001806 sp<FakeWindowHandle>::make(application, mDispatcher,
1807 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001808
1809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1810
1811 // Window closes its channel, but the window remains.
1812 window->destroyReceiver();
1813 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1814}
1815
Arthur Hungb92218b2018-08-14 12:00:21 +08001816TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001817 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001818 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1819 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001820
Arthur Hung72d8dc32020-03-28 00:48:39 +00001821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1823 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001825
1826 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001827 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001828}
1829
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001830TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001832 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1833 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001834
1835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1836 // Inject a MotionEvent to an unknown display.
1837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1840
1841 // Window should receive motion event.
1842 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1843}
1844
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001845/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001846 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001847 * This test serves as a sanity check for the next test, where setInputWindows is
1848 * called twice.
1849 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001850TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001851 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001852 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1853 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001854 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001855
1856 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001858 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1859 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001860 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001861
1862 // Window should receive motion event.
1863 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1864}
1865
1866/**
1867 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001868 */
1869TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001870 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001871 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1872 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001873 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001874
1875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001878 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1879 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001881
1882 // Window should receive motion event.
1883 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1884}
1885
Arthur Hungb92218b2018-08-14 12:00:21 +08001886// The foreground window should receive the first touch down event.
1887TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001888 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001889 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001890 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001891 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001892 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001893
Arthur Hung72d8dc32020-03-28 00:48:39 +00001894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1897 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001898
1899 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001900 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001901 windowSecond->assertNoEvents();
1902}
1903
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001904/**
1905 * Two windows: A top window, and a wallpaper behind the window.
1906 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1907 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001908 * 1. foregroundWindow <-- dup touch to wallpaper
1909 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001910 */
1911TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1912 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1913 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001914 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001915 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001916 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001917 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001918 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001919
1920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1921 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1922 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1923 {100, 200}))
1924 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1925
1926 // Both foreground window and its wallpaper should receive the touch down
1927 foregroundWindow->consumeMotionDown();
1928 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1929
1930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1931 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1932 ADISPLAY_ID_DEFAULT, {110, 200}))
1933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1934
1935 foregroundWindow->consumeMotionMove();
1936 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1937
1938 // Now the foreground window goes away, but the wallpaper stays
1939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1940 foregroundWindow->consumeMotionCancel();
1941 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1942 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1943}
1944
1945/**
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001946 * Two fingers down on the window, and lift off the first finger.
1947 * Next, cancel the gesture to the window by removing the window. Make sure that the CANCEL event
1948 * contains a single pointer.
1949 */
1950TEST_F(InputDispatcherTest, CancelAfterPointer0Up) {
1951 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1952 sp<FakeWindowHandle> window =
1953 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1954
1955 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1956 NotifyMotionArgs args;
1957 // First touch pointer down on right window
1958 mDispatcher->notifyMotion(&(
1959 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001960 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001961 .build()));
1962 // Second touch pointer down
1963 mDispatcher->notifyMotion(&(
1964 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1965
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001966 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
1967 .pointer(PointerBuilder(1, ToolType::FINGER).x(110).y(100))
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001968 .build()));
1969 // First touch pointer lifts. The second one remains down
1970 mDispatcher->notifyMotion(&(
1971 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1972
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001973 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
1974 .pointer(PointerBuilder(1, ToolType::FINGER).x(110).y(100))
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001975 .build()));
1976 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
1977 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
1978 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
1979
1980 // Remove the window. The gesture should be canceled
1981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
1982 const std::map<int32_t, PointF> expectedPointers{{1, PointF{110, 100}}};
1983 window->consumeMotionEvent(
1984 AllOf(WithMotionAction(ACTION_CANCEL), WithPointers(expectedPointers)));
1985}
1986
1987/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001988 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1989 * with the following differences:
1990 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1991 * clean up the connection.
1992 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1993 * Ensure that there's no crash in the dispatcher.
1994 */
1995TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1997 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001998 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001999 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002000 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002001 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002002 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002003
2004 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
2005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2006 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2007 {100, 200}))
2008 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2009
2010 // Both foreground window and its wallpaper should receive the touch down
2011 foregroundWindow->consumeMotionDown();
2012 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2013
2014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2015 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2016 ADISPLAY_ID_DEFAULT, {110, 200}))
2017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2018
2019 foregroundWindow->consumeMotionMove();
2020 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2021
2022 // Wallpaper closes its channel, but the window remains.
2023 wallpaperWindow->destroyReceiver();
2024 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
2025
2026 // Now the foreground window goes away, but the wallpaper stays, even though its channel
2027 // is no longer valid.
2028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
2029 foregroundWindow->consumeMotionCancel();
2030}
2031
Arthur Hungc539dbb2022-12-08 07:45:36 +00002032class ShouldSplitTouchFixture : public InputDispatcherTest,
2033 public ::testing::WithParamInterface<bool> {};
2034INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
2035 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002036/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002037 * A single window that receives touch (on top), and a wallpaper window underneath it.
2038 * The top window gets a multitouch gesture.
2039 * Ensure that wallpaper gets the same gesture.
2040 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00002041TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002042 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002043 sp<FakeWindowHandle> foregroundWindow =
2044 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2045 foregroundWindow->setDupTouchToWallpaper(true);
2046 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002047
2048 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002049 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002050 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002051
Arthur Hungc539dbb2022-12-08 07:45:36 +00002052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002053
2054 // Touch down on top window
2055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2056 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2057 {100, 100}))
2058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2059
2060 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00002061 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002062 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2063
2064 // Second finger down on the top window
2065 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002066 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002067 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002068 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(100))
2069 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002070 .build();
2071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2072 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2073 InputEventInjectionSync::WAIT_FOR_RESULT))
2074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2075
Harry Cutts33476232023-01-30 19:57:29 +00002076 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
2077 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002078 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002079
2080 const MotionEvent secondFingerUpEvent =
2081 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2082 .displayId(ADISPLAY_ID_DEFAULT)
2083 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002084 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(100))
2085 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002086 .build();
2087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2088 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
2089 InputEventInjectionSync::WAIT_FOR_RESULT))
2090 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2091 foregroundWindow->consumeMotionPointerUp(0);
2092 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2093
2094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08002095 injectMotionEvent(mDispatcher,
2096 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2097 AINPUT_SOURCE_TOUCHSCREEN)
2098 .displayId(ADISPLAY_ID_DEFAULT)
2099 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2100 .pointer(PointerBuilder(/* id */ 1,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002101 ToolType::FINGER)
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08002102 .x(100)
2103 .y(100))
2104 .build(),
2105 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002106 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2107 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2108 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002109}
2110
2111/**
2112 * Two windows: a window on the left and window on the right.
2113 * A third window, wallpaper, is behind both windows, and spans both top windows.
2114 * The first touch down goes to the left window. A second pointer touches down on the right window.
2115 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2116 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2117 * ACTION_POINTER_DOWN(1).
2118 */
2119TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2120 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2121 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002122 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002123 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002124 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002125
2126 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002127 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002128 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002129 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002130
2131 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002132 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002133 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002134 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002135
2136 mDispatcher->setInputWindows(
2137 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2138
2139 // Touch down on left window
2140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2141 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2142 {100, 100}))
2143 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2144
2145 // Both foreground window and its wallpaper should receive the touch down
2146 leftWindow->consumeMotionDown();
2147 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2148
2149 // Second finger down on the right window
2150 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002151 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002152 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002153 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(100))
2154 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002155 .build();
2156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2157 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2158 InputEventInjectionSync::WAIT_FOR_RESULT))
2159 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2160
2161 leftWindow->consumeMotionMove();
2162 // Since the touch is split, right window gets ACTION_DOWN
2163 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002164 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002165 expectedWallpaperFlags);
2166
2167 // Now, leftWindow, which received the first finger, disappears.
2168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2169 leftWindow->consumeMotionCancel();
2170 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2171 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2172
2173 // The pointer that's still down on the right window moves, and goes to the right window only.
2174 // As far as the dispatcher's concerned though, both pointers are still present.
2175 const MotionEvent secondFingerMoveEvent =
2176 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2177 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002178 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(100))
2179 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002180 .build();
2181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2182 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2183 InputEventInjectionSync::WAIT_FOR_RESULT));
2184 rightWindow->consumeMotionMove();
2185
2186 leftWindow->assertNoEvents();
2187 rightWindow->assertNoEvents();
2188 wallpaperWindow->assertNoEvents();
2189}
2190
Arthur Hungc539dbb2022-12-08 07:45:36 +00002191/**
2192 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2193 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2194 * The right window should receive ACTION_DOWN.
2195 */
2196TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002197 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002198 sp<FakeWindowHandle> leftWindow =
2199 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2200 leftWindow->setFrame(Rect(0, 0, 200, 200));
2201 leftWindow->setDupTouchToWallpaper(true);
2202 leftWindow->setSlippery(true);
2203
2204 sp<FakeWindowHandle> rightWindow =
2205 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2206 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002207
2208 sp<FakeWindowHandle> wallpaperWindow =
2209 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2210 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002211
Arthur Hungc539dbb2022-12-08 07:45:36 +00002212 mDispatcher->setInputWindows(
2213 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002214
Arthur Hungc539dbb2022-12-08 07:45:36 +00002215 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002216 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2217 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002218 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002219 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002220
2221 // Both foreground window and its wallpaper should receive the touch down
2222 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002223 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2224
Arthur Hungc539dbb2022-12-08 07:45:36 +00002225 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002227 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2228 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002229 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2230
Arthur Hungc539dbb2022-12-08 07:45:36 +00002231 leftWindow->consumeMotionCancel();
2232 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2233 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002234}
2235
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002236/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002237 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2238 * interactive, it might stop sending this flag.
2239 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2240 * to have a consistent input stream.
2241 *
2242 * Test procedure:
2243 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2244 * DOWN (new gesture).
2245 *
2246 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2247 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2248 *
2249 * We technically just need a single window here, but we are using two windows (spy on top and a
2250 * regular window below) to emulate the actual situation where it happens on the device.
2251 */
2252TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2253 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2254 sp<FakeWindowHandle> spyWindow =
2255 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2256 spyWindow->setFrame(Rect(0, 0, 200, 200));
2257 spyWindow->setTrustedOverlay(true);
2258 spyWindow->setSpy(true);
2259
2260 sp<FakeWindowHandle> window =
2261 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2262 window->setFrame(Rect(0, 0, 200, 200));
2263
2264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2265 const int32_t touchDeviceId = 4;
2266 NotifyMotionArgs args;
2267
2268 // Two pointers down
2269 mDispatcher->notifyMotion(&(
2270 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2271 .deviceId(touchDeviceId)
2272 .policyFlags(DEFAULT_POLICY_FLAGS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002273 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002274 .build()));
2275
2276 mDispatcher->notifyMotion(&(
2277 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2278 .deviceId(touchDeviceId)
2279 .policyFlags(DEFAULT_POLICY_FLAGS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002280 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
2281 .pointer(PointerBuilder(1, ToolType::FINGER).x(120).y(120))
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002282 .build()));
2283 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2284 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2285 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2286 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2287
2288 // Cancel the current gesture. Send the cancel without the default policy flags.
2289 mDispatcher->notifyMotion(&(
2290 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2291 .deviceId(touchDeviceId)
2292 .policyFlags(0)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002293 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
2294 .pointer(PointerBuilder(1, ToolType::FINGER).x(120).y(120))
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002295 .build()));
2296 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2297 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2298
2299 // We don't need to reset the device to reproduce the issue, but the reset event typically
2300 // follows, so we keep it here to model the actual listener behaviour more closely.
2301 NotifyDeviceResetArgs resetArgs;
2302 resetArgs.id = 1; // arbitrary id
2303 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2304 resetArgs.deviceId = touchDeviceId;
2305 mDispatcher->notifyDeviceReset(&resetArgs);
2306
2307 // Start new gesture
2308 mDispatcher->notifyMotion(&(
2309 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2310 .deviceId(touchDeviceId)
2311 .policyFlags(DEFAULT_POLICY_FLAGS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002312 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002313 .build()));
2314 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2315 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2316
2317 // No more events
2318 spyWindow->assertNoEvents();
2319 window->assertNoEvents();
2320}
2321
2322/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002323 * Two windows: a window on the left and a window on the right.
2324 * Mouse is hovered from the right window into the left window.
2325 * Next, we tap on the left window, where the cursor was last seen.
2326 * The second tap is done onto the right window.
2327 * The mouse and tap are from two different devices.
2328 * We technically don't need to set the downtime / eventtime for these events, but setting these
2329 * explicitly helps during debugging.
2330 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2331 * In the buggy implementation, a tap on the right window would cause a crash.
2332 */
2333TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2334 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2335 sp<FakeWindowHandle> leftWindow =
2336 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2337 leftWindow->setFrame(Rect(0, 0, 200, 200));
2338
2339 sp<FakeWindowHandle> rightWindow =
2340 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2341 rightWindow->setFrame(Rect(200, 0, 400, 200));
2342
2343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2344 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2345 // stale.
2346 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2347 const int32_t mouseDeviceId = 6;
2348 const int32_t touchDeviceId = 4;
2349 // Move the cursor from right
2350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2351 injectMotionEvent(mDispatcher,
2352 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2353 AINPUT_SOURCE_MOUSE)
2354 .deviceId(mouseDeviceId)
2355 .downTime(baseTime + 10)
2356 .eventTime(baseTime + 20)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002357 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002358 .x(300)
2359 .y(100))
2360 .build()));
2361 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2362
2363 // .. to the left window
2364 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2365 injectMotionEvent(mDispatcher,
2366 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2367 AINPUT_SOURCE_MOUSE)
2368 .deviceId(mouseDeviceId)
2369 .downTime(baseTime + 10)
2370 .eventTime(baseTime + 30)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002371 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002372 .x(110)
2373 .y(100))
2374 .build()));
2375 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2376 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2377 // Now tap the left window
2378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2379 injectMotionEvent(mDispatcher,
2380 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2381 AINPUT_SOURCE_TOUCHSCREEN)
2382 .deviceId(touchDeviceId)
2383 .downTime(baseTime + 40)
2384 .eventTime(baseTime + 40)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002385 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002386 .x(100)
2387 .y(100))
2388 .build()));
2389 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2390 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2391
2392 // release tap
2393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2394 injectMotionEvent(mDispatcher,
2395 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2396 AINPUT_SOURCE_TOUCHSCREEN)
2397 .deviceId(touchDeviceId)
2398 .downTime(baseTime + 40)
2399 .eventTime(baseTime + 50)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002400 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002401 .x(100)
2402 .y(100))
2403 .build()));
2404 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2405
2406 // Tap the window on the right
2407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2408 injectMotionEvent(mDispatcher,
2409 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2410 AINPUT_SOURCE_TOUCHSCREEN)
2411 .deviceId(touchDeviceId)
2412 .downTime(baseTime + 60)
2413 .eventTime(baseTime + 60)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002414 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002415 .x(300)
2416 .y(100))
2417 .build()));
2418 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2419
2420 // release tap
2421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2422 injectMotionEvent(mDispatcher,
2423 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2424 AINPUT_SOURCE_TOUCHSCREEN)
2425 .deviceId(touchDeviceId)
2426 .downTime(baseTime + 60)
2427 .eventTime(baseTime + 70)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002428 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002429 .x(300)
2430 .y(100))
2431 .build()));
2432 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2433
2434 // No more events
2435 leftWindow->assertNoEvents();
2436 rightWindow->assertNoEvents();
2437}
2438
2439/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002440 * Two windows: a window on the left and a window on the right.
2441 * Mouse is clicked on the left window and remains down. Touch is touched on the right and remains
2442 * down. Then, on the left window, also place second touch pointer down.
2443 * This test tries to reproduce a crash.
2444 * In the buggy implementation, second pointer down on the left window would cause a crash.
2445 */
2446TEST_F(InputDispatcherTest, MultiDeviceSplitTouch) {
2447 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2448 sp<FakeWindowHandle> leftWindow =
2449 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2450 leftWindow->setFrame(Rect(0, 0, 200, 200));
2451
2452 sp<FakeWindowHandle> rightWindow =
2453 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2454 rightWindow->setFrame(Rect(200, 0, 400, 200));
2455
2456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2457
2458 const int32_t touchDeviceId = 4;
2459 const int32_t mouseDeviceId = 6;
2460 NotifyMotionArgs args;
2461
2462 // Start hovering over the left window
2463 mDispatcher->notifyMotion(&(
2464 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2465 .deviceId(mouseDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002466 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002467 .build()));
2468 leftWindow->consumeMotionEvent(
2469 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2470
2471 // Mouse down on left window
2472 mDispatcher->notifyMotion(&(
2473 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2474 .deviceId(mouseDeviceId)
2475 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002476 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002477 .build()));
2478
2479 leftWindow->consumeMotionEvent(
2480 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
2481 leftWindow->consumeMotionEvent(
2482 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2483
2484 mDispatcher->notifyMotion(&(
2485 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2486 .deviceId(mouseDeviceId)
2487 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2488 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002489 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002490 .build()));
2491 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2492
2493 // First touch pointer down on right window
2494 mDispatcher->notifyMotion(&(
2495 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2496 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002497 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002498 .build()));
2499 leftWindow->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2500
2501 rightWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2502
2503 // Second touch pointer down on left window
2504 mDispatcher->notifyMotion(&(
2505 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2506 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002507 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
2508 .pointer(PointerBuilder(1, ToolType::FINGER).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002509 .build()));
2510 leftWindow->consumeMotionEvent(
2511 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2512 // This MOVE event is not necessary (doesn't carry any new information), but it's there in the
2513 // current implementation.
2514 const std::map<int32_t, PointF> expectedPointers{{0, PointF{100, 100}}};
2515 rightWindow->consumeMotionEvent(
2516 AllOf(WithMotionAction(ACTION_MOVE), WithPointers(expectedPointers)));
2517
2518 leftWindow->assertNoEvents();
2519 rightWindow->assertNoEvents();
2520}
2521
2522/**
2523 * On a single window, use two different devices: mouse and touch.
2524 * Touch happens first, with two pointers going down, and then the first pointer leaving.
2525 * Mouse is clicked next, which causes the touch stream to be aborted with ACTION_CANCEL.
2526 * Finally, a second touch pointer goes down again. Ensure the second touch pointer is ignored,
2527 * because the mouse is currently down, and a POINTER_DOWN event from the touchscreen does not
2528 * represent a new gesture.
2529 */
2530TEST_F(InputDispatcherTest, MixedTouchAndMouseWithPointerDown) {
2531 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2532 sp<FakeWindowHandle> window =
2533 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2534 window->setFrame(Rect(0, 0, 400, 400));
2535
2536 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2537
2538 const int32_t touchDeviceId = 4;
2539 const int32_t mouseDeviceId = 6;
2540 NotifyMotionArgs args;
2541
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08002542 // First touch pointer down
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002543 mDispatcher->notifyMotion(&(
2544 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2545 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002546 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002547 .build()));
2548 // Second touch pointer down
2549 mDispatcher->notifyMotion(&(
2550 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2551 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002552 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
2553 .pointer(PointerBuilder(1, ToolType::FINGER).x(350).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002554 .build()));
2555 // First touch pointer lifts. The second one remains down
2556 mDispatcher->notifyMotion(&(
2557 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2558 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002559 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
2560 .pointer(PointerBuilder(1, ToolType::FINGER).x(350).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002561 .build()));
2562 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2563 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2564 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
2565
2566 // Mouse down. The touch should be canceled
2567 mDispatcher->notifyMotion(&(
2568 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2569 .deviceId(mouseDeviceId)
2570 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002571 .pointer(PointerBuilder(0, ToolType::MOUSE).x(320).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002572 .build()));
2573
2574 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08002575 WithPointerCount(1u)));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002576 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2577
2578 mDispatcher->notifyMotion(&(
2579 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2580 .deviceId(mouseDeviceId)
2581 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2582 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002583 .pointer(PointerBuilder(0, ToolType::MOUSE).x(320).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002584 .build()));
2585 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2586
2587 // Second touch pointer down.
2588 mDispatcher->notifyMotion(&(
2589 args = MotionArgsBuilder(POINTER_0_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2590 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002591 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
2592 .pointer(PointerBuilder(1, ToolType::FINGER).x(350).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002593 .build()));
2594 // The pointer_down event should be ignored
2595 window->assertNoEvents();
2596}
2597
2598/**
Siarhei Vishniakou56e79092023-02-21 19:13:16 -08002599 * Inject a touch down and then send a new event via 'notifyMotion'. Ensure the new event cancels
2600 * the injected event.
2601 */
2602TEST_F(InputDispatcherTest, UnfinishedInjectedEvent) {
2603 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2604 sp<FakeWindowHandle> window =
2605 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2606 window->setFrame(Rect(0, 0, 400, 400));
2607
2608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2609
2610 const int32_t touchDeviceId = 4;
2611 NotifyMotionArgs args;
2612 // Pretend a test injects an ACTION_DOWN mouse event, but forgets to lift up the touch after
2613 // completion.
2614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2615 injectMotionEvent(mDispatcher,
2616 MotionEventBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2617 .deviceId(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002618 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakou56e79092023-02-21 19:13:16 -08002619 .x(50)
2620 .y(50))
2621 .build()));
2622 window->consumeMotionEvent(
2623 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2624
2625 // Now a real touch comes. Rather than crashing or dropping the real event, the injected pointer
2626 // should be canceled and the new gesture should take over.
2627 mDispatcher->notifyMotion(&(
2628 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2629 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002630 .pointer(PointerBuilder(0, ToolType::FINGER).x(300).y(100))
Siarhei Vishniakou56e79092023-02-21 19:13:16 -08002631 .build()));
2632
2633 window->consumeMotionEvent(
2634 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2635 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2636}
2637
2638/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002639 * This test is similar to the test above, but the sequence of injected events is different.
2640 *
2641 * Two windows: a window on the left and a window on the right.
2642 * Mouse is hovered over the left window.
2643 * Next, we tap on the left window, where the cursor was last seen.
2644 *
2645 * After that, we inject one finger down onto the right window, and then a second finger down onto
2646 * the left window.
2647 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2648 * window (first), and then another on the left window (second).
2649 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2650 * In the buggy implementation, second finger down on the left window would cause a crash.
2651 */
2652TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2653 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2654 sp<FakeWindowHandle> leftWindow =
2655 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2656 leftWindow->setFrame(Rect(0, 0, 200, 200));
2657
2658 sp<FakeWindowHandle> rightWindow =
2659 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2660 rightWindow->setFrame(Rect(200, 0, 400, 200));
2661
2662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2663
2664 const int32_t mouseDeviceId = 6;
2665 const int32_t touchDeviceId = 4;
2666 // Hover over the left window. Keep the cursor there.
2667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2668 injectMotionEvent(mDispatcher,
2669 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2670 AINPUT_SOURCE_MOUSE)
2671 .deviceId(mouseDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002672 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002673 .x(50)
2674 .y(50))
2675 .build()));
2676 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2677
2678 // Tap on left window
2679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2680 injectMotionEvent(mDispatcher,
2681 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2682 AINPUT_SOURCE_TOUCHSCREEN)
2683 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002684 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002685 .x(100)
2686 .y(100))
2687 .build()));
2688
2689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2690 injectMotionEvent(mDispatcher,
2691 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2692 AINPUT_SOURCE_TOUCHSCREEN)
2693 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002694 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002695 .x(100)
2696 .y(100))
2697 .build()));
2698 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2699 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2700 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2701
2702 // First finger down on right window
2703 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2704 injectMotionEvent(mDispatcher,
2705 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2706 AINPUT_SOURCE_TOUCHSCREEN)
2707 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002708 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002709 .x(300)
2710 .y(100))
2711 .build()));
2712 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2713
2714 // Second finger down on the left window
2715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2716 injectMotionEvent(mDispatcher,
2717 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2718 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002719 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002720 .x(300)
2721 .y(100))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002722 .pointer(PointerBuilder(1, ToolType::FINGER)
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002723 .x(100)
2724 .y(100))
2725 .build()));
2726 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2727 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2728
2729 // No more events
2730 leftWindow->assertNoEvents();
2731 rightWindow->assertNoEvents();
2732}
2733
2734/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002735 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2736 * While the touch is down, new hover events from the stylus device should be ignored. After the
2737 * touch is gone, stylus hovering should start working again.
2738 */
2739TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2740 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2741 sp<FakeWindowHandle> window =
2742 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2743 window->setFrame(Rect(0, 0, 200, 200));
2744
2745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2746
2747 const int32_t stylusDeviceId = 5;
2748 const int32_t touchDeviceId = 4;
2749 // Start hovering with stylus
2750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2751 injectMotionEvent(mDispatcher,
2752 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2753 AINPUT_SOURCE_STYLUS)
2754 .deviceId(stylusDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002755 .pointer(PointerBuilder(0, ToolType::STYLUS)
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002756 .x(50)
2757 .y(50))
2758 .build()));
2759 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2760
2761 // Finger down on the window
2762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2763 injectMotionEvent(mDispatcher,
2764 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2765 AINPUT_SOURCE_TOUCHSCREEN)
2766 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002767 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002768 .x(100)
2769 .y(100))
2770 .build()));
2771 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2772 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2773
2774 // Try to continue hovering with stylus. Since we are already down, injection should fail
2775 ASSERT_EQ(InputEventInjectionResult::FAILED,
2776 injectMotionEvent(mDispatcher,
2777 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2778 AINPUT_SOURCE_STYLUS)
2779 .deviceId(stylusDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002780 .pointer(PointerBuilder(0, ToolType::STYLUS)
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002781 .x(50)
2782 .y(50))
2783 .build()));
2784 // No event should be sent. This event should be ignored because a pointer from another device
2785 // is already down.
2786
2787 // Lift up the finger
2788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2789 injectMotionEvent(mDispatcher,
2790 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2791 AINPUT_SOURCE_TOUCHSCREEN)
2792 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002793 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002794 .x(100)
2795 .y(100))
2796 .build()));
2797 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2798
2799 // Now that the touch is gone, stylus hovering should start working again
2800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2801 injectMotionEvent(mDispatcher,
2802 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2803 AINPUT_SOURCE_STYLUS)
2804 .deviceId(stylusDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002805 .pointer(PointerBuilder(0, ToolType::STYLUS)
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002806 .x(50)
2807 .y(50))
2808 .build()));
2809 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2810 // No more events
2811 window->assertNoEvents();
2812}
2813
2814/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002815 * A spy window above a window with no input channel.
2816 * Start hovering with a stylus device, and then tap with it.
2817 * Ensure spy window receives the entire sequence.
2818 */
2819TEST_F(InputDispatcherTest, StylusHoverAndDownNoInputChannel) {
2820 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2821 sp<FakeWindowHandle> spyWindow =
2822 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2823 spyWindow->setFrame(Rect(0, 0, 200, 200));
2824 spyWindow->setTrustedOverlay(true);
2825 spyWindow->setSpy(true);
2826 sp<FakeWindowHandle> window =
2827 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2828 window->setNoInputChannel(true);
2829 window->setFrame(Rect(0, 0, 200, 200));
2830
2831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2832
2833 NotifyMotionArgs args;
2834
2835 // Start hovering with stylus
2836 mDispatcher->notifyMotion(
2837 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002838 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002839 .build()));
2840 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2841 // Stop hovering
2842 mDispatcher->notifyMotion(
2843 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002844 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002845 .build()));
2846 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2847
2848 // Stylus touches down
2849 mDispatcher->notifyMotion(
2850 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002851 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002852 .build()));
2853 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2854
2855 // Stylus goes up
2856 mDispatcher->notifyMotion(
2857 &(args = MotionArgsBuilder(ACTION_UP, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002858 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002859 .build()));
2860 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_UP));
2861
2862 // Again hover
2863 mDispatcher->notifyMotion(
2864 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002865 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002866 .build()));
2867 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2868 // Stop hovering
2869 mDispatcher->notifyMotion(
2870 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002871 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002872 .build()));
2873 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2874
2875 // No more events
2876 spyWindow->assertNoEvents();
2877 window->assertNoEvents();
2878}
2879
2880/**
2881 * Start hovering with a mouse, and then tap with a touch device. Pilfer the touch stream.
2882 * Next, click with the mouse device. Both windows (spy and regular) should receive the new mouse
2883 * ACTION_DOWN event because that's a new gesture, and pilfering should no longer be active.
2884 * While the mouse is down, new move events from the touch device should be ignored.
2885 */
2886TEST_F(InputDispatcherTest, TouchPilferAndMouseMove) {
2887 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2888 sp<FakeWindowHandle> spyWindow =
2889 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2890 spyWindow->setFrame(Rect(0, 0, 200, 200));
2891 spyWindow->setTrustedOverlay(true);
2892 spyWindow->setSpy(true);
2893 sp<FakeWindowHandle> window =
2894 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2895 window->setFrame(Rect(0, 0, 200, 200));
2896
2897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2898
2899 const int32_t mouseDeviceId = 7;
2900 const int32_t touchDeviceId = 4;
2901 NotifyMotionArgs args;
2902
2903 // Hover a bit with mouse first
2904 mDispatcher->notifyMotion(&(
2905 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2906 .deviceId(mouseDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002907 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002908 .build()));
2909 spyWindow->consumeMotionEvent(
2910 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2911 window->consumeMotionEvent(
2912 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2913
2914 // Start touching
2915 mDispatcher->notifyMotion(
2916 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2917 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002918 .pointer(PointerBuilder(0, ToolType::FINGER).x(50).y(50))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002919 .build()));
2920 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2921 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2922 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2923 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2924
2925 mDispatcher->notifyMotion(
2926 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2927 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002928 .pointer(PointerBuilder(0, ToolType::FINGER).x(55).y(55))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002929 .build()));
2930 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2931 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2932
2933 // Pilfer the stream
2934 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2935 window->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2936
2937 mDispatcher->notifyMotion(
2938 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2939 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002940 .pointer(PointerBuilder(0, ToolType::FINGER).x(60).y(60))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002941 .build()));
2942 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2943
2944 // Mouse down
2945 mDispatcher->notifyMotion(&(
2946 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2947 .deviceId(mouseDeviceId)
2948 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002949 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002950 .build()));
2951
2952 spyWindow->consumeMotionEvent(
2953 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId)));
2954 spyWindow->consumeMotionEvent(
2955 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2956 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2957
2958 mDispatcher->notifyMotion(&(
2959 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2960 .deviceId(mouseDeviceId)
2961 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2962 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002963 .pointer(PointerBuilder(0, ToolType::MOUSE).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002964 .build()));
2965 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2966 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2967
2968 // Mouse move!
2969 mDispatcher->notifyMotion(&(
2970 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_MOUSE)
2971 .deviceId(mouseDeviceId)
2972 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002973 .pointer(PointerBuilder(0, ToolType::MOUSE).x(110).y(110))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002974 .build()));
2975 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2976 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2977
2978 // Touch move!
2979 mDispatcher->notifyMotion(
2980 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2981 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002982 .pointer(PointerBuilder(0, ToolType::FINGER).x(65).y(65))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002983 .build()));
2984
2985 // No more events
2986 spyWindow->assertNoEvents();
2987 window->assertNoEvents();
2988}
2989
2990/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002991 * On the display, have a single window, and also an area where there's no window.
2992 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2993 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2994 */
2995TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2997 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002998 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002999
3000 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
3001 NotifyMotionArgs args;
3002
3003 // Touch down on the empty space
3004 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
3005
3006 mDispatcher->waitForIdle();
3007 window->assertNoEvents();
3008
3009 // Now touch down on the window with another pointer
3010 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
3011 mDispatcher->waitForIdle();
3012 window->consumeMotionDown();
3013}
3014
3015/**
3016 * Same test as above, but instead of touching the empty space, the first touch goes to
3017 * non-touchable window.
3018 */
3019TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
3020 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3021 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003022 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003023 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3024 window1->setTouchable(false);
3025 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003026 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003027 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3028
3029 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3030
3031 NotifyMotionArgs args;
3032 // Touch down on the non-touchable window
3033 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3034
3035 mDispatcher->waitForIdle();
3036 window1->assertNoEvents();
3037 window2->assertNoEvents();
3038
3039 // Now touch down on the window with another pointer
3040 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3041 mDispatcher->waitForIdle();
3042 window2->consumeMotionDown();
3043}
3044
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003045/**
3046 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
3047 * to the event time of the first ACTION_DOWN sent to the particular window.
3048 */
3049TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
3050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3051 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003052 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003053 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3054 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003055 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003056 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3057
3058 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3059
3060 NotifyMotionArgs args;
3061 // Touch down on the first window
3062 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3063
3064 mDispatcher->waitForIdle();
3065 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003066 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003067 window2->assertNoEvents();
3068 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
3069 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
3070 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
3071
3072 // Now touch down on the window with another pointer
3073 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3074 mDispatcher->waitForIdle();
3075 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003076 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003077 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
3078 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
3079 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
3080 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
3081
3082 // Now move the pointer on the second window
3083 mDispatcher->notifyMotion(
3084 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
3085 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003086 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003087
3088 // Now add new touch down on the second window
3089 mDispatcher->notifyMotion(
3090 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
3091 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003092 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003093
3094 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
3095 window1->consumeMotionMove();
3096 window1->assertNoEvents();
3097
3098 // Now move the pointer on the first window
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08003099 mDispatcher->notifyMotion(&(
3100 args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}, {150, 50}})));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003101 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003102 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003103
3104 mDispatcher->notifyMotion(&(
3105 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
3106 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003107 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003108}
3109
Garfield Tandf26e862020-07-01 20:18:19 -07003110TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003111 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003112 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003113 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003114 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003115 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003116 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003117 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003118
3119 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3120
3121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
3122
3123 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003124 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003125 injectMotionEvent(mDispatcher,
3126 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3127 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003128 .pointer(PointerBuilder(0, ToolType::MOUSE).x(900).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003129 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003130 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003131
3132 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003134 injectMotionEvent(mDispatcher,
3135 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3136 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003137 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003138 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003139 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3140 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003141
3142 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003144 injectMotionEvent(mDispatcher,
3145 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3146 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003147 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003148 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003149 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3150 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003151
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003153 injectMotionEvent(mDispatcher,
3154 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3155 AINPUT_SOURCE_MOUSE)
3156 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3157 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003158 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003159 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003160 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
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_RELEASE,
3165 AINPUT_SOURCE_MOUSE)
3166 .buttonState(0)
3167 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003168 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003169 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003170 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003171
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003173 injectMotionEvent(mDispatcher,
3174 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3175 .buttonState(0)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003176 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003177 .build()));
3178 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3179
3180 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003182 injectMotionEvent(mDispatcher,
3183 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3184 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003185 .pointer(PointerBuilder(0, ToolType::MOUSE).x(900).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003186 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003187 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003188
3189 // No more events
3190 windowLeft->assertNoEvents();
3191 windowRight->assertNoEvents();
3192}
3193
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003194/**
3195 * Put two fingers down (and don't release them) and click the mouse button.
3196 * The clicking of mouse is a new ACTION_DOWN event. Since it's from a different device, the
3197 * currently active gesture should be canceled, and the new one should proceed.
3198 */
3199TEST_F(InputDispatcherTest, TwoPointersDownMouseClick) {
3200 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3201 sp<FakeWindowHandle> window =
3202 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3203 window->setFrame(Rect(0, 0, 600, 800));
3204
3205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3206
3207 const int32_t touchDeviceId = 4;
3208 const int32_t mouseDeviceId = 6;
3209 NotifyMotionArgs args;
3210
3211 // Two pointers down
3212 mDispatcher->notifyMotion(&(
3213 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3214 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003215 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003216 .build()));
3217
3218 mDispatcher->notifyMotion(&(
3219 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3220 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003221 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
3222 .pointer(PointerBuilder(1, ToolType::FINGER).x(120).y(120))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003223 .build()));
3224 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
3225 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
3226
3227 // Inject a series of mouse events for a mouse click
3228 mDispatcher->notifyMotion(&(
3229 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3230 .deviceId(mouseDeviceId)
3231 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003232 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003233 .build()));
3234 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
3235 WithPointerCount(2u)));
3236 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
3237
3238 mDispatcher->notifyMotion(&(
3239 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
3240 .deviceId(mouseDeviceId)
3241 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3242 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003243 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003244 .build()));
3245 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
3246
3247 // Try to send more touch events while the mouse is down. Since it's a continuation of an
3248 // already canceled gesture, it should be ignored.
3249 mDispatcher->notifyMotion(&(
3250 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
3251 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003252 .pointer(PointerBuilder(0, ToolType::FINGER).x(101).y(101))
3253 .pointer(PointerBuilder(1, ToolType::FINGER).x(121).y(121))
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003254 .build()));
3255 window->assertNoEvents();
3256}
3257
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003258TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
3259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3260
3261 sp<FakeWindowHandle> spyWindow =
3262 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3263 spyWindow->setFrame(Rect(0, 0, 600, 800));
3264 spyWindow->setTrustedOverlay(true);
3265 spyWindow->setSpy(true);
3266 sp<FakeWindowHandle> window =
3267 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3268 window->setFrame(Rect(0, 0, 600, 800));
3269
3270 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3272
3273 // Send mouse cursor to the window
3274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3275 injectMotionEvent(mDispatcher,
3276 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3277 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003278 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003279 .x(100)
3280 .y(100))
3281 .build()));
3282
3283 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3284 WithSource(AINPUT_SOURCE_MOUSE)));
3285 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3286 WithSource(AINPUT_SOURCE_MOUSE)));
3287
3288 window->assertNoEvents();
3289 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003290}
3291
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003292TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
3293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3294
3295 sp<FakeWindowHandle> spyWindow =
3296 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3297 spyWindow->setFrame(Rect(0, 0, 600, 800));
3298 spyWindow->setTrustedOverlay(true);
3299 spyWindow->setSpy(true);
3300 sp<FakeWindowHandle> window =
3301 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3302 window->setFrame(Rect(0, 0, 600, 800));
3303
3304 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3306
3307 // Send mouse cursor to the window
3308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3309 injectMotionEvent(mDispatcher,
3310 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3311 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003312 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003313 .x(100)
3314 .y(100))
3315 .build()));
3316
3317 // Move mouse cursor
3318 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3319 injectMotionEvent(mDispatcher,
3320 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3321 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003322 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003323 .x(110)
3324 .y(110))
3325 .build()));
3326
3327 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3328 WithSource(AINPUT_SOURCE_MOUSE)));
3329 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3330 WithSource(AINPUT_SOURCE_MOUSE)));
3331 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3332 WithSource(AINPUT_SOURCE_MOUSE)));
3333 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3334 WithSource(AINPUT_SOURCE_MOUSE)));
3335 // Touch down on the window
3336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3337 injectMotionEvent(mDispatcher,
3338 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3339 AINPUT_SOURCE_TOUCHSCREEN)
3340 .deviceId(SECOND_DEVICE_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003341 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003342 .x(200)
3343 .y(200))
3344 .build()));
3345 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3346 WithSource(AINPUT_SOURCE_MOUSE)));
3347 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3348 WithSource(AINPUT_SOURCE_MOUSE)));
3349 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3350 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3351 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3352 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3353
3354 // pilfer the motion, retaining the gesture on the spy window.
3355 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
3356 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3357 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3358
3359 // Touch UP on the window
3360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3361 injectMotionEvent(mDispatcher,
3362 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3363 AINPUT_SOURCE_TOUCHSCREEN)
3364 .deviceId(SECOND_DEVICE_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003365 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003366 .x(200)
3367 .y(200))
3368 .build()));
3369 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3370 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3371
3372 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
3373 // to send a new gesture. It should again go to both windows (spy and the window below), just
3374 // like the first gesture did, before pilfering. The window configuration has not changed.
3375
3376 // One more tap - DOWN
3377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3378 injectMotionEvent(mDispatcher,
3379 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3380 AINPUT_SOURCE_TOUCHSCREEN)
3381 .deviceId(SECOND_DEVICE_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003382 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003383 .x(250)
3384 .y(250))
3385 .build()));
3386 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3387 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3388 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3389 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3390
3391 // Touch UP on the window
3392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3393 injectMotionEvent(mDispatcher,
3394 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3395 AINPUT_SOURCE_TOUCHSCREEN)
3396 .deviceId(SECOND_DEVICE_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003397 .pointer(PointerBuilder(0, ToolType::FINGER)
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003398 .x(250)
3399 .y(250))
3400 .build()));
3401 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3402 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3403 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3404 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3405
3406 window->assertNoEvents();
3407 spyWindow->assertNoEvents();
3408}
3409
Garfield Tandf26e862020-07-01 20:18:19 -07003410// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
3411// directly in this test.
3412TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003413 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003414 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003415 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003416 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003417
3418 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3419
3420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3421
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003423 injectMotionEvent(mDispatcher,
3424 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3425 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003426 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003427 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003428 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003429 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003430 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003431 injectMotionEvent(mDispatcher,
3432 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3433 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003434 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003435 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003436 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3437 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003438
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003440 injectMotionEvent(mDispatcher,
3441 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3442 AINPUT_SOURCE_MOUSE)
3443 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3444 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003445 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003446 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003447 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003448
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003450 injectMotionEvent(mDispatcher,
3451 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3452 AINPUT_SOURCE_MOUSE)
3453 .buttonState(0)
3454 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003455 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003456 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003457 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003458
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003460 injectMotionEvent(mDispatcher,
3461 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3462 .buttonState(0)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003463 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003464 .build()));
3465 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3466
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003468 injectMotionEvent(mDispatcher,
3469 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
3470 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003471 .pointer(PointerBuilder(0, ToolType::MOUSE).x(300).y(400))
Garfield Tandf26e862020-07-01 20:18:19 -07003472 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003473 window->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003474}
3475
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003476/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003477 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
3478 * is generated.
3479 */
3480TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
3481 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3482 sp<FakeWindowHandle> window =
3483 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3484 window->setFrame(Rect(0, 0, 1200, 800));
3485
3486 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3487
3488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3489
3490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3491 injectMotionEvent(mDispatcher,
3492 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3493 AINPUT_SOURCE_MOUSE)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003494 .pointer(PointerBuilder(0, ToolType::MOUSE)
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003495 .x(300)
3496 .y(400))
3497 .build()));
3498 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3499
3500 // Remove the window, but keep the channel.
3501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3502 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3503}
3504
3505/**
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003506 * If mouse is hovering when the touch goes down, the hovering should be stopped via HOVER_EXIT.
3507 */
3508TEST_F(InputDispatcherTest, TouchDownAfterMouseHover) {
3509 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3510 sp<FakeWindowHandle> window =
3511 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3512 window->setFrame(Rect(0, 0, 100, 100));
3513
3514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3515
3516 const int32_t mouseDeviceId = 7;
3517 const int32_t touchDeviceId = 4;
3518 NotifyMotionArgs args;
3519
3520 // Start hovering with the mouse
3521 mDispatcher->notifyMotion(
3522 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
3523 .deviceId(mouseDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003524 .pointer(PointerBuilder(0, ToolType::MOUSE).x(10).y(10))
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003525 .build()));
3526 window->consumeMotionEvent(
3527 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
3528
3529 // Touch goes down
3530 mDispatcher->notifyMotion(
3531 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3532 .deviceId(touchDeviceId)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003533 .pointer(PointerBuilder(0, ToolType::FINGER).x(50).y(50))
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003534 .build()));
3535
3536 window->consumeMotionEvent(
3537 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
3538 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
3539}
3540
3541/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003542 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003543 * The tap causes a HOVER_EXIT event to be generated because the current event
3544 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003545 */
3546TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3548 sp<FakeWindowHandle> window =
3549 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3550 window->setFrame(Rect(0, 0, 100, 100));
3551
3552 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3553
3554 // Inject a hover_move from mouse.
3555 NotifyMotionArgs motionArgs =
3556 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3557 ADISPLAY_ID_DEFAULT, {{50, 50}});
3558 motionArgs.xCursorPosition = 50;
3559 motionArgs.yCursorPosition = 50;
3560 mDispatcher->notifyMotion(&motionArgs);
3561 ASSERT_NO_FATAL_FAILURE(
3562 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3563 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003564
3565 // Tap on the window
3566 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3567 ADISPLAY_ID_DEFAULT, {{10, 10}});
3568 mDispatcher->notifyMotion(&motionArgs);
3569 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003570 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3571 WithSource(AINPUT_SOURCE_MOUSE))));
3572
3573 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003574 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3575 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3576
3577 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3578 ADISPLAY_ID_DEFAULT, {{10, 10}});
3579 mDispatcher->notifyMotion(&motionArgs);
3580 ASSERT_NO_FATAL_FAILURE(
3581 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3582 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3583}
3584
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003585TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3587 sp<FakeWindowHandle> windowDefaultDisplay =
3588 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3589 ADISPLAY_ID_DEFAULT);
3590 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3591 sp<FakeWindowHandle> windowSecondDisplay =
3592 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3593 SECOND_DISPLAY_ID);
3594 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3595
3596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3597 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3598
3599 // Set cursor position in window in default display and check that hover enter and move
3600 // events are generated.
3601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3602 injectMotionEvent(mDispatcher,
3603 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3604 AINPUT_SOURCE_MOUSE)
3605 .displayId(ADISPLAY_ID_DEFAULT)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003606 .pointer(PointerBuilder(0, ToolType::MOUSE)
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003607 .x(300)
3608 .y(600))
3609 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003610 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003611
3612 // Remove all windows in secondary display and check that no event happens on window in
3613 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003614 mDispatcher->setInputWindows(
3615 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003616 windowDefaultDisplay->assertNoEvents();
3617
3618 // Move cursor position in window in default display and check that only hover move
3619 // event is generated and not hover enter event.
3620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3621 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3623 injectMotionEvent(mDispatcher,
3624 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3625 AINPUT_SOURCE_MOUSE)
3626 .displayId(ADISPLAY_ID_DEFAULT)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003627 .pointer(PointerBuilder(0, ToolType::MOUSE)
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003628 .x(400)
3629 .y(700))
3630 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003631 windowDefaultDisplay->consumeMotionEvent(
3632 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3633 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003634 windowDefaultDisplay->assertNoEvents();
3635}
3636
Garfield Tan00f511d2019-06-12 16:55:40 -07003637TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003638 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003639
3640 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003641 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003642 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003643 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003644 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003645 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003646
3647 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3648
Arthur Hung72d8dc32020-03-28 00:48:39 +00003649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003650
3651 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3652 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003654 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003655 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003656 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003657 windowRight->assertNoEvents();
3658}
3659
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003660TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003662 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3663 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003664 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003665
Arthur Hung72d8dc32020-03-28 00:48:39 +00003666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003667 setFocusedWindow(window);
3668
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003669 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003670
3671 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3672 mDispatcher->notifyKey(&keyArgs);
3673
3674 // Window should receive key down event.
3675 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3676
3677 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3678 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003679 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003680 mDispatcher->notifyDeviceReset(&args);
3681 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3682 AKEY_EVENT_FLAG_CANCELED);
3683}
3684
3685TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003686 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003687 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3688 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003689
Arthur Hung72d8dc32020-03-28 00:48:39 +00003690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003691
3692 NotifyMotionArgs motionArgs =
3693 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3694 ADISPLAY_ID_DEFAULT);
3695 mDispatcher->notifyMotion(&motionArgs);
3696
3697 // Window should receive motion down event.
3698 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3699
3700 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3701 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003702 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003703 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003704 window->consumeMotionEvent(
3705 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003706}
3707
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003708TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003710 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3711 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003712 window->setFocusable(true);
3713
3714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3715 setFocusedWindow(window);
3716
3717 window->consumeFocusEvent(true);
3718
3719 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3720 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3721 const nsecs_t injectTime = keyArgs.eventTime;
3722 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3723 mDispatcher->notifyKey(&keyArgs);
3724 // The dispatching time should be always greater than or equal to intercept key timeout.
3725 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3726 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3727 std::chrono::nanoseconds(interceptKeyTimeout).count());
3728}
3729
3730TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3731 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003732 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3733 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003734 window->setFocusable(true);
3735
3736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3737 setFocusedWindow(window);
3738
3739 window->consumeFocusEvent(true);
3740
3741 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3742 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3743 mFakePolicy->setInterceptKeyTimeout(150ms);
3744 mDispatcher->notifyKey(&keyDown);
3745 mDispatcher->notifyKey(&keyUp);
3746
3747 // Window should receive key event immediately when same key up.
3748 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3749 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3750}
3751
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003752/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003753 * Two windows. First is a regular window. Second does not overlap with the first, and has
3754 * WATCH_OUTSIDE_TOUCH.
3755 * Both windows are owned by the same UID.
3756 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3757 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3758 */
3759TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3761 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3762 "First Window", ADISPLAY_ID_DEFAULT);
3763 window->setFrame(Rect{0, 0, 100, 100});
3764
3765 sp<FakeWindowHandle> outsideWindow =
3766 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3767 ADISPLAY_ID_DEFAULT);
3768 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3769 outsideWindow->setWatchOutsideTouch(true);
3770 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3772
3773 // Tap on first window.
3774 NotifyMotionArgs motionArgs =
3775 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3776 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3777 mDispatcher->notifyMotion(&motionArgs);
3778 window->consumeMotionDown();
3779 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3780 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3781 outsideWindow->consumeMotionEvent(
3782 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3783}
3784
3785/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003786 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3787 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3788 * ACTION_OUTSIDE event is sent per gesture.
3789 */
3790TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3791 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3792 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003793 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3794 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003795 window->setWatchOutsideTouch(true);
3796 window->setFrame(Rect{0, 0, 100, 100});
3797 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003798 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3799 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003800 secondWindow->setFrame(Rect{100, 100, 200, 200});
3801 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003802 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3803 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003804 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3806
3807 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3808 NotifyMotionArgs motionArgs =
3809 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3810 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3811 mDispatcher->notifyMotion(&motionArgs);
3812 window->assertNoEvents();
3813 secondWindow->assertNoEvents();
3814
3815 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3816 // Now, `window` should get ACTION_OUTSIDE.
3817 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3818 {PointF{-10, -10}, PointF{105, 105}});
3819 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003820 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3821 window->consumeMotionEvent(
3822 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003823 secondWindow->consumeMotionDown();
3824 thirdWindow->assertNoEvents();
3825
3826 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3827 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3828 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3829 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3830 mDispatcher->notifyMotion(&motionArgs);
3831 window->assertNoEvents();
3832 secondWindow->consumeMotionMove();
3833 thirdWindow->consumeMotionDown();
3834}
3835
Prabir Pradhan814fe082022-07-22 20:22:18 +00003836TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3837 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003838 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3839 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003840 window->setFocusable(true);
3841
3842 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3843 setFocusedWindow(window);
3844
3845 window->consumeFocusEvent(true);
3846
3847 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3848 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3849 mDispatcher->notifyKey(&keyDown);
3850 mDispatcher->notifyKey(&keyUp);
3851
3852 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3853 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3854
3855 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3856 mDispatcher->onWindowInfosChanged({}, {});
3857
3858 window->consumeFocusEvent(false);
3859
3860 mDispatcher->notifyKey(&keyDown);
3861 mDispatcher->notifyKey(&keyUp);
3862 window->assertNoEvents();
3863}
3864
Arthur Hung96483742022-11-15 03:30:48 +00003865TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3866 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3867 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3868 "Fake Window", ADISPLAY_ID_DEFAULT);
3869 // Ensure window is non-split and have some transform.
3870 window->setPreventSplitting(true);
3871 window->setWindowOffset(20, 40);
3872 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3873
3874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3875 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3876 {50, 50}))
3877 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3878 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3879
3880 const MotionEvent secondFingerDownEvent =
3881 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3882 .displayId(ADISPLAY_ID_DEFAULT)
3883 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003884 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(50).y(50))
3885 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003886 .build();
3887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3888 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3889 InputEventInjectionSync::WAIT_FOR_RESULT))
3890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3891
3892 const MotionEvent* event = window->consumeMotion();
3893 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3894 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3895 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3896 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3897 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3898}
3899
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003900/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003901 * Ensure the correct coordinate spaces are used by InputDispatcher.
3902 *
3903 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3904 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3905 * space.
3906 */
3907class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3908public:
3909 void SetUp() override {
3910 InputDispatcherTest::SetUp();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003911 removeAllWindowsAndDisplays();
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003912 }
3913
3914 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3915 gui::DisplayInfo info;
3916 info.displayId = displayId;
3917 info.transform = transform;
3918 mDisplayInfos.push_back(std::move(info));
3919 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3920 }
3921
3922 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3923 mWindowInfos.push_back(*windowHandle->getInfo());
3924 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3925 }
3926
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003927 void removeAllWindowsAndDisplays() {
3928 mDisplayInfos.clear();
3929 mWindowInfos.clear();
3930 }
3931
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003932 // Set up a test scenario where the display has a scaled projection and there are two windows
3933 // on the display.
3934 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3935 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3936 // respectively.
3937 ui::Transform displayTransform;
3938 displayTransform.set(2, 0, 0, 4);
3939 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3940
3941 std::shared_ptr<FakeApplicationHandle> application =
3942 std::make_shared<FakeApplicationHandle>();
3943
3944 // Add two windows to the display. Their frames are represented in the display space.
3945 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003946 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3947 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003948 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3949 addWindow(firstWindow);
3950
3951 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003952 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3953 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003954 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3955 addWindow(secondWindow);
3956 return {std::move(firstWindow), std::move(secondWindow)};
3957 }
3958
3959private:
3960 std::vector<gui::DisplayInfo> mDisplayInfos;
3961 std::vector<gui::WindowInfo> mWindowInfos;
3962};
3963
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003964TEST_F(InputDispatcherDisplayProjectionTest, HitTestCoordinateSpaceConsistency) {
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003965 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3966 // Send down to the first window. The point is represented in the display space. The point is
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003967 // selected so that if the hit test was performed with the point and the bounds being in
3968 // different coordinate spaces, the event would end up in the incorrect window.
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003969 NotifyMotionArgs downMotionArgs =
3970 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3971 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3972 mDispatcher->notifyMotion(&downMotionArgs);
3973
3974 firstWindow->consumeMotionDown();
3975 secondWindow->assertNoEvents();
3976}
3977
3978// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3979// the event should be treated as being in the logical display space.
3980TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3981 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3982 // Send down to the first window. The point is represented in the logical display space. The
3983 // point is selected so that if the hit test was done in logical display space, then it would
3984 // end up in the incorrect window.
3985 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3986 PointF{75 * 2, 55 * 4});
3987
3988 firstWindow->consumeMotionDown();
3989 secondWindow->assertNoEvents();
3990}
3991
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003992// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3993// event should be treated as being in the logical display space.
3994TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3995 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3996
3997 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3998 ui::Transform injectedEventTransform;
3999 injectedEventTransform.set(matrix);
4000 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
4001 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
4002
4003 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
4004 .displayId(ADISPLAY_ID_DEFAULT)
4005 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07004006 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004007 .x(untransformedPoint.x)
4008 .y(untransformedPoint.y))
4009 .build();
4010 event.transform(matrix);
4011
4012 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
4013 InputEventInjectionSync::WAIT_FOR_RESULT);
4014
4015 firstWindow->consumeMotionDown();
4016 secondWindow->assertNoEvents();
4017}
4018
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07004019TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
4020 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4021
4022 // Send down to the second window.
4023 NotifyMotionArgs downMotionArgs =
4024 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4025 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
4026 mDispatcher->notifyMotion(&downMotionArgs);
4027
4028 firstWindow->assertNoEvents();
4029 const MotionEvent* event = secondWindow->consumeMotion();
4030 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
4031
4032 // Ensure that the events from the "getRaw" API are in logical display coordinates.
4033 EXPECT_EQ(300, event->getRawX(0));
4034 EXPECT_EQ(880, event->getRawY(0));
4035
4036 // Ensure that the x and y values are in the window's coordinate space.
4037 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
4038 // the logical display space. This will be the origin of the window space.
4039 EXPECT_EQ(100, event->getX(0));
4040 EXPECT_EQ(80, event->getY(0));
4041}
4042
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004043/** Ensure consistent behavior of InputDispatcher in all orientations. */
4044class InputDispatcherDisplayOrientationFixture
4045 : public InputDispatcherDisplayProjectionTest,
4046 public ::testing::WithParamInterface<ui::Rotation> {};
4047
4048// This test verifies the touchable region of a window for all rotations of the display by tapping
4049// in different locations on the display, specifically points close to the four corners of a
4050// window.
4051TEST_P(InputDispatcherDisplayOrientationFixture, HitTestInDifferentOrientations) {
4052 constexpr static int32_t displayWidth = 400;
4053 constexpr static int32_t displayHeight = 800;
4054
4055 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4056
4057 const auto rotation = GetParam();
4058
4059 // Set up the display with the specified rotation.
4060 const bool isRotated = rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270;
4061 const int32_t logicalDisplayWidth = isRotated ? displayHeight : displayWidth;
4062 const int32_t logicalDisplayHeight = isRotated ? displayWidth : displayHeight;
4063 const ui::Transform displayTransform(ui::Transform::toRotationFlags(rotation),
4064 logicalDisplayWidth, logicalDisplayHeight);
4065 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
4066
4067 // Create a window with its bounds determined in the logical display.
4068 const Rect frameInLogicalDisplay(100, 100, 200, 300);
4069 const Rect frameInDisplay = displayTransform.inverse().transform(frameInLogicalDisplay);
4070 sp<FakeWindowHandle> window =
4071 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
4072 window->setFrame(frameInDisplay, displayTransform);
4073 addWindow(window);
4074
4075 // The following points in logical display space should be inside the window.
4076 static const std::array<vec2, 4> insidePoints{
4077 {{100, 100}, {199.99, 100}, {100, 299.99}, {199.99, 299.99}}};
4078 for (const auto pointInsideWindow : insidePoints) {
4079 const vec2 p = displayTransform.inverse().transform(pointInsideWindow);
4080 const PointF pointInDisplaySpace{p.x, p.y};
4081 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4082 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4083 mDispatcher->notifyMotion(&down);
4084 window->consumeMotionDown();
4085
4086 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4087 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4088 mDispatcher->notifyMotion(&up);
4089 window->consumeMotionUp();
4090 }
4091
4092 // The following points in logical display space should be outside the window.
4093 static const std::array<vec2, 5> outsidePoints{
4094 {{200, 100}, {100, 300}, {200, 300}, {100, 99.99}, {99.99, 100}}};
4095 for (const auto pointOutsideWindow : outsidePoints) {
4096 const vec2 p = displayTransform.inverse().transform(pointOutsideWindow);
4097 const PointF pointInDisplaySpace{p.x, p.y};
4098 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4099 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4100 mDispatcher->notifyMotion(&down);
4101
4102 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4103 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4104 mDispatcher->notifyMotion(&up);
4105 }
4106 window->assertNoEvents();
4107}
4108
4109// Run the precision tests for all rotations.
4110INSTANTIATE_TEST_SUITE_P(InputDispatcherDisplayOrientationTests,
4111 InputDispatcherDisplayOrientationFixture,
4112 ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
4113 ui::ROTATION_270),
4114 [](const testing::TestParamInfo<ui::Rotation>& testParamInfo) {
4115 return ftl::enum_string(testParamInfo.param);
4116 });
4117
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004118using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
4119 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004120
4121class TransferTouchFixture : public InputDispatcherTest,
4122 public ::testing::WithParamInterface<TransferFunction> {};
4123
4124TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07004125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126
4127 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004128 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004129 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4130 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004131 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004132 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004133 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4134 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004135 sp<FakeWindowHandle> wallpaper =
4136 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
4137 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004138 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00004139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004140
4141 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004142 NotifyMotionArgs downMotionArgs =
4143 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4144 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004145 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004146
Svet Ganov5d3bc372020-01-26 23:11:07 -08004147 // Only the first window should get the down event
4148 firstWindow->consumeMotionDown();
4149 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004150 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004151
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004152 // Transfer touch to the second window
4153 TransferFunction f = GetParam();
4154 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4155 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004156 // The first window gets cancel and the second gets down
4157 firstWindow->consumeMotionCancel();
4158 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004159 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004160
4161 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004162 NotifyMotionArgs upMotionArgs =
4163 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4164 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004165 mDispatcher->notifyMotion(&upMotionArgs);
4166 // The first window gets no events and the second gets up
4167 firstWindow->assertNoEvents();
4168 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004169 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004170}
4171
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004172/**
4173 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4174 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4175 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4176 * natural to the user.
4177 * In this test, we are sending a pointer to both spy window and first window. We then try to
4178 * transfer touch to the second window. The dispatcher should identify the first window as the
4179 * one that should lose the gesture, and therefore the action should be to move the gesture from
4180 * the first window to the second.
4181 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4182 * the other API, as well.
4183 */
4184TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4185 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4186
4187 // Create a couple of windows + a spy window
4188 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004189 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004190 spyWindow->setTrustedOverlay(true);
4191 spyWindow->setSpy(true);
4192 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004193 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004194 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004195 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004196
4197 // Add the windows to the dispatcher
4198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4199
4200 // Send down to the first window
4201 NotifyMotionArgs downMotionArgs =
4202 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4203 ADISPLAY_ID_DEFAULT);
4204 mDispatcher->notifyMotion(&downMotionArgs);
4205 // Only the first window and spy should get the down event
4206 spyWindow->consumeMotionDown();
4207 firstWindow->consumeMotionDown();
4208
4209 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4210 // if f === 'transferTouch'.
4211 TransferFunction f = GetParam();
4212 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4213 ASSERT_TRUE(success);
4214 // The first window gets cancel and the second gets down
4215 firstWindow->consumeMotionCancel();
4216 secondWindow->consumeMotionDown();
4217
4218 // Send up event to the second window
4219 NotifyMotionArgs upMotionArgs =
4220 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4221 ADISPLAY_ID_DEFAULT);
4222 mDispatcher->notifyMotion(&upMotionArgs);
4223 // The first window gets no events and the second+spy get up
4224 firstWindow->assertNoEvents();
4225 spyWindow->consumeMotionUp();
4226 secondWindow->consumeMotionUp();
4227}
4228
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004229TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004230 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004231
4232 PointF touchPoint = {10, 10};
4233
4234 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004235 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004236 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4237 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004238 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004239 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004240 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4241 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004242 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004243
4244 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246
4247 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004248 NotifyMotionArgs downMotionArgs =
4249 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4250 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004251 mDispatcher->notifyMotion(&downMotionArgs);
4252 // Only the first window should get the down event
4253 firstWindow->consumeMotionDown();
4254 secondWindow->assertNoEvents();
4255
4256 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004257 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004258 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004259 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004260 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4261 // Only the first window should get the pointer down event
4262 firstWindow->consumeMotionPointerDown(1);
4263 secondWindow->assertNoEvents();
4264
4265 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004266 TransferFunction f = GetParam();
4267 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4268 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004269 // The first window gets cancel and the second gets down and pointer down
4270 firstWindow->consumeMotionCancel();
4271 secondWindow->consumeMotionDown();
4272 secondWindow->consumeMotionPointerDown(1);
4273
4274 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004275 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004276 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004277 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004278 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4279 // The first window gets nothing and the second gets pointer up
4280 firstWindow->assertNoEvents();
4281 secondWindow->consumeMotionPointerUp(1);
4282
4283 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004284 NotifyMotionArgs upMotionArgs =
4285 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4286 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004287 mDispatcher->notifyMotion(&upMotionArgs);
4288 // The first window gets nothing and the second gets up
4289 firstWindow->assertNoEvents();
4290 secondWindow->consumeMotionUp();
4291}
4292
Arthur Hungc539dbb2022-12-08 07:45:36 +00004293TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4294 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4295
4296 // Create a couple of windows
4297 sp<FakeWindowHandle> firstWindow =
4298 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4299 ADISPLAY_ID_DEFAULT);
4300 firstWindow->setDupTouchToWallpaper(true);
4301 sp<FakeWindowHandle> secondWindow =
4302 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4303 ADISPLAY_ID_DEFAULT);
4304 secondWindow->setDupTouchToWallpaper(true);
4305
4306 sp<FakeWindowHandle> wallpaper1 =
4307 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4308 wallpaper1->setIsWallpaper(true);
4309
4310 sp<FakeWindowHandle> wallpaper2 =
4311 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4312 wallpaper2->setIsWallpaper(true);
4313 // Add the windows to the dispatcher
4314 mDispatcher->setInputWindows(
4315 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4316
4317 // Send down to the first window
4318 NotifyMotionArgs downMotionArgs =
4319 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4320 ADISPLAY_ID_DEFAULT);
4321 mDispatcher->notifyMotion(&downMotionArgs);
4322
4323 // Only the first window should get the down event
4324 firstWindow->consumeMotionDown();
4325 secondWindow->assertNoEvents();
4326 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4327 wallpaper2->assertNoEvents();
4328
4329 // Transfer touch focus to the second window
4330 TransferFunction f = GetParam();
4331 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4332 ASSERT_TRUE(success);
4333
4334 // The first window gets cancel and the second gets down
4335 firstWindow->consumeMotionCancel();
4336 secondWindow->consumeMotionDown();
4337 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4338 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4339
4340 // Send up event to the second window
4341 NotifyMotionArgs upMotionArgs =
4342 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4343 ADISPLAY_ID_DEFAULT);
4344 mDispatcher->notifyMotion(&upMotionArgs);
4345 // The first window gets no events and the second gets up
4346 firstWindow->assertNoEvents();
4347 secondWindow->consumeMotionUp();
4348 wallpaper1->assertNoEvents();
4349 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4350}
4351
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004352// For the cases of single pointer touch and two pointers non-split touch, the api's
4353// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4354// for the case where there are multiple pointers split across several windows.
4355INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4356 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004357 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4358 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004359 return dispatcher->transferTouch(destChannelToken,
4360 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004361 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004362 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4363 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004364 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004365 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004366 }));
4367
Svet Ganov5d3bc372020-01-26 23:11:07 -08004368TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004369 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004370
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004371 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004372 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4373 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004374 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004375
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004376 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004377 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4378 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004379 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004380
4381 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004383
4384 PointF pointInFirst = {300, 200};
4385 PointF pointInSecond = {300, 600};
4386
4387 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004388 NotifyMotionArgs firstDownMotionArgs =
4389 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4390 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004391 mDispatcher->notifyMotion(&firstDownMotionArgs);
4392 // Only the first window should get the down event
4393 firstWindow->consumeMotionDown();
4394 secondWindow->assertNoEvents();
4395
4396 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004397 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004398 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004399 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004400 mDispatcher->notifyMotion(&secondDownMotionArgs);
4401 // The first window gets a move and the second a down
4402 firstWindow->consumeMotionMove();
4403 secondWindow->consumeMotionDown();
4404
4405 // Transfer touch focus to the second window
4406 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4407 // The first window gets cancel and the new gets pointer down (it already saw down)
4408 firstWindow->consumeMotionCancel();
4409 secondWindow->consumeMotionPointerDown(1);
4410
4411 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004412 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004413 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004414 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004415 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4416 // The first window gets nothing and the second gets pointer up
4417 firstWindow->assertNoEvents();
4418 secondWindow->consumeMotionPointerUp(1);
4419
4420 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004421 NotifyMotionArgs upMotionArgs =
4422 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4423 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004424 mDispatcher->notifyMotion(&upMotionArgs);
4425 // The first window gets nothing and the second gets up
4426 firstWindow->assertNoEvents();
4427 secondWindow->consumeMotionUp();
4428}
4429
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004430// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4431// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4432// touch is not supported, so the touch should continue on those windows and the transferred-to
4433// window should get nothing.
4434TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4435 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4436
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004437 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004438 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4439 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004440 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004441
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004442 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004443 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4444 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004445 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004446
4447 // Add the windows to the dispatcher
4448 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4449
4450 PointF pointInFirst = {300, 200};
4451 PointF pointInSecond = {300, 600};
4452
4453 // Send down to the first window
4454 NotifyMotionArgs firstDownMotionArgs =
4455 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4456 ADISPLAY_ID_DEFAULT, {pointInFirst});
4457 mDispatcher->notifyMotion(&firstDownMotionArgs);
4458 // Only the first window should get the down event
4459 firstWindow->consumeMotionDown();
4460 secondWindow->assertNoEvents();
4461
4462 // Send down to the second window
4463 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004464 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004465 {pointInFirst, pointInSecond});
4466 mDispatcher->notifyMotion(&secondDownMotionArgs);
4467 // The first window gets a move and the second a down
4468 firstWindow->consumeMotionMove();
4469 secondWindow->consumeMotionDown();
4470
4471 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004472 const bool transferred =
4473 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004474 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4475 ASSERT_FALSE(transferred);
4476 firstWindow->assertNoEvents();
4477 secondWindow->assertNoEvents();
4478
4479 // The rest of the dispatch should proceed as normal
4480 // Send pointer up to the second window
4481 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004482 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004483 {pointInFirst, pointInSecond});
4484 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4485 // The first window gets MOVE and the second gets pointer up
4486 firstWindow->consumeMotionMove();
4487 secondWindow->consumeMotionUp();
4488
4489 // Send up event to the first window
4490 NotifyMotionArgs upMotionArgs =
4491 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4492 ADISPLAY_ID_DEFAULT);
4493 mDispatcher->notifyMotion(&upMotionArgs);
4494 // The first window gets nothing and the second gets up
4495 firstWindow->consumeMotionUp();
4496 secondWindow->assertNoEvents();
4497}
4498
Arthur Hungabbb9d82021-09-01 14:52:30 +00004499// This case will create two windows and one mirrored window on the default display and mirror
4500// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4501// the windows info of second display before default display.
4502TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4504 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004505 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004506 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004507 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004508 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004509 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004510
4511 sp<FakeWindowHandle> mirrorWindowInPrimary =
4512 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4513 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004514
4515 sp<FakeWindowHandle> firstWindowInSecondary =
4516 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4517 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004518
4519 sp<FakeWindowHandle> secondWindowInSecondary =
4520 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4521 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004522
4523 // Update window info, let it find window handle of second display first.
4524 mDispatcher->setInputWindows(
4525 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4526 {ADISPLAY_ID_DEFAULT,
4527 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4528
4529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4531 {50, 50}))
4532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4533
4534 // Window should receive motion event.
4535 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4536
4537 // Transfer touch focus
4538 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4539 secondWindowInPrimary->getToken()));
4540 // The first window gets cancel.
4541 firstWindowInPrimary->consumeMotionCancel();
4542 secondWindowInPrimary->consumeMotionDown();
4543
4544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4545 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4546 ADISPLAY_ID_DEFAULT, {150, 50}))
4547 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4548 firstWindowInPrimary->assertNoEvents();
4549 secondWindowInPrimary->consumeMotionMove();
4550
4551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4552 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4553 {150, 50}))
4554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4555 firstWindowInPrimary->assertNoEvents();
4556 secondWindowInPrimary->consumeMotionUp();
4557}
4558
4559// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4560// 'transferTouch' api.
4561TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4563 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004564 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004565 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004566 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004567 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004568 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004569
4570 sp<FakeWindowHandle> mirrorWindowInPrimary =
4571 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4572 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004573
4574 sp<FakeWindowHandle> firstWindowInSecondary =
4575 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4576 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004577
4578 sp<FakeWindowHandle> secondWindowInSecondary =
4579 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4580 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004581
4582 // Update window info, let it find window handle of second display first.
4583 mDispatcher->setInputWindows(
4584 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4585 {ADISPLAY_ID_DEFAULT,
4586 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4587
4588 // Touch on second display.
4589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4591 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4592
4593 // Window should receive motion event.
4594 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4595
4596 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004597 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004598
4599 // The first window gets cancel.
4600 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4601 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4602
4603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4604 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4605 SECOND_DISPLAY_ID, {150, 50}))
4606 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4607 firstWindowInPrimary->assertNoEvents();
4608 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4609
4610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4611 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4613 firstWindowInPrimary->assertNoEvents();
4614 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4615}
4616
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004617TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004618 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004619 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4620 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004621
Vishnu Nair47074b82020-08-14 11:54:47 -07004622 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004624 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004625
4626 window->consumeFocusEvent(true);
4627
4628 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4629 mDispatcher->notifyKey(&keyArgs);
4630
4631 // Window should receive key down event.
4632 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4633}
4634
4635TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004636 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004637 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4638 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004639
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004641
4642 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4643 mDispatcher->notifyKey(&keyArgs);
4644 mDispatcher->waitForIdle();
4645
4646 window->assertNoEvents();
4647}
4648
4649// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4650TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004651 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004652 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4653 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004654
Arthur Hung72d8dc32020-03-28 00:48:39 +00004655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004656
4657 // Send key
4658 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4659 mDispatcher->notifyKey(&keyArgs);
4660 // Send motion
4661 NotifyMotionArgs motionArgs =
4662 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4663 ADISPLAY_ID_DEFAULT);
4664 mDispatcher->notifyMotion(&motionArgs);
4665
4666 // Window should receive only the motion event
4667 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4668 window->assertNoEvents(); // Key event or focus event will not be received
4669}
4670
arthurhungea3f4fc2020-12-21 23:18:53 +08004671TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4672 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4673
arthurhungea3f4fc2020-12-21 23:18:53 +08004674 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004675 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4676 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004677 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004678
arthurhungea3f4fc2020-12-21 23:18:53 +08004679 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004680 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4681 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004682 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004683
4684 // Add the windows to the dispatcher
4685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4686
4687 PointF pointInFirst = {300, 200};
4688 PointF pointInSecond = {300, 600};
4689
4690 // Send down to the first window
4691 NotifyMotionArgs firstDownMotionArgs =
4692 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4693 ADISPLAY_ID_DEFAULT, {pointInFirst});
4694 mDispatcher->notifyMotion(&firstDownMotionArgs);
4695 // Only the first window should get the down event
4696 firstWindow->consumeMotionDown();
4697 secondWindow->assertNoEvents();
4698
4699 // Send down to the second window
4700 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004701 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004702 {pointInFirst, pointInSecond});
4703 mDispatcher->notifyMotion(&secondDownMotionArgs);
4704 // The first window gets a move and the second a down
4705 firstWindow->consumeMotionMove();
4706 secondWindow->consumeMotionDown();
4707
4708 // Send pointer cancel to the second window
4709 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004710 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004711 {pointInFirst, pointInSecond});
4712 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4713 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4714 // The first window gets move and the second gets cancel.
4715 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4716 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4717
4718 // Send up event.
4719 NotifyMotionArgs upMotionArgs =
4720 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4721 ADISPLAY_ID_DEFAULT);
4722 mDispatcher->notifyMotion(&upMotionArgs);
4723 // The first window gets up and the second gets nothing.
4724 firstWindow->consumeMotionUp();
4725 secondWindow->assertNoEvents();
4726}
4727
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004728TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4729 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4730
4731 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004732 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4734 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4735 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4736 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4737
Harry Cutts33476232023-01-30 19:57:29 +00004738 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004739 window->assertNoEvents();
4740 mDispatcher->waitForIdle();
4741}
4742
chaviwd1c23182019-12-20 18:44:56 -08004743class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004744public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004745 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004746 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004747 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004748 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004749 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004750 }
4751
chaviwd1c23182019-12-20 18:44:56 -08004752 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4753
4754 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4755 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4756 expectedDisplayId, expectedFlags);
4757 }
4758
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4760
4761 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4762
chaviwd1c23182019-12-20 18:44:56 -08004763 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4764 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4765 expectedDisplayId, expectedFlags);
4766 }
4767
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004768 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4769 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4770 expectedDisplayId, expectedFlags);
4771 }
4772
chaviwd1c23182019-12-20 18:44:56 -08004773 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4774 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4775 expectedDisplayId, expectedFlags);
4776 }
4777
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004778 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004779 mInputReceiver->consumeMotionEvent(
4780 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4781 WithDisplayId(expectedDisplayId),
4782 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004783 }
4784
Arthur Hungfbfa5722021-11-16 02:45:54 +00004785 void consumeMotionPointerDown(int32_t pointerIdx) {
4786 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4787 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4788 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004789 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004790 }
4791
Evan Rosky84f07f02021-04-16 10:42:42 -07004792 MotionEvent* consumeMotion() {
4793 InputEvent* event = mInputReceiver->consume();
4794 if (!event) {
4795 ADD_FAILURE() << "No event was produced";
4796 return nullptr;
4797 }
4798 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4799 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4800 return nullptr;
4801 }
4802 return static_cast<MotionEvent*>(event);
4803 }
4804
chaviwd1c23182019-12-20 18:44:56 -08004805 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4806
4807private:
4808 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004809};
4810
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004811using InputDispatcherMonitorTest = InputDispatcherTest;
4812
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004813/**
4814 * Two entities that receive touch: A window, and a global monitor.
4815 * The touch goes to the window, and then the window disappears.
4816 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4817 * for the monitor, as well.
4818 * 1. foregroundWindow
4819 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4820 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004821TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4823 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004824 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004825
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004826 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004827
4828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4830 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4831 {100, 200}))
4832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4833
4834 // Both the foreground window and the global monitor should receive the touch down
4835 window->consumeMotionDown();
4836 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4837
4838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4839 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4840 ADISPLAY_ID_DEFAULT, {110, 200}))
4841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4842
4843 window->consumeMotionMove();
4844 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4845
4846 // Now the foreground window goes away
4847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4848 window->consumeMotionCancel();
4849 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4850
4851 // If more events come in, there will be no more foreground window to send them to. This will
4852 // cause a cancel for the monitor, as well.
4853 ASSERT_EQ(InputEventInjectionResult::FAILED,
4854 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4855 ADISPLAY_ID_DEFAULT, {120, 200}))
4856 << "Injection should fail because the window was removed";
4857 window->assertNoEvents();
4858 // Global monitor now gets the cancel
4859 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4860}
4861
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004862TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004863 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004864 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4865 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004867
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004868 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004869
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004871 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004872 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004873 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004874 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004875}
4876
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004877TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4878 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004879
Chris Yea209fde2020-07-22 13:54:51 -07004880 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004881 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4882 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004884
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004886 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004887 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004888 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004889 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004890
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004891 // Pilfer pointers from the monitor.
4892 // This should not do anything and the window should continue to receive events.
4893 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004894
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004896 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4897 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004899
4900 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4901 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004902}
4903
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004904TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004905 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004906 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4907 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4909 window->setWindowOffset(20, 40);
4910 window->setWindowTransform(0, 1, -1, 0);
4911
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004912 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004913
4914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4915 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4916 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4917 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4918 MotionEvent* event = monitor.consumeMotion();
4919 // Even though window has transform, gesture monitor must not.
4920 ASSERT_EQ(ui::Transform(), event->getTransform());
4921}
4922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004923TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004924 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004925 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004926
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004927 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004928 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004929 << "Injection should fail if there is a monitor, but no touchable window";
4930 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004931}
4932
chaviw81e2bb92019-12-18 15:03:51 -08004933TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004934 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004935 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4936 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004937
Arthur Hung72d8dc32020-03-28 00:48:39 +00004938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004939
4940 NotifyMotionArgs motionArgs =
4941 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4942 ADISPLAY_ID_DEFAULT);
4943
4944 mDispatcher->notifyMotion(&motionArgs);
4945 // Window should receive motion down event.
4946 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4947
4948 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004949 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004950 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4951 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4952 motionArgs.pointerCoords[0].getX() - 10);
4953
4954 mDispatcher->notifyMotion(&motionArgs);
4955 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004956 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004957}
4958
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004959/**
4960 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4961 * the device default right away. In the test scenario, we check both the default value,
4962 * and the action of enabling / disabling.
4963 */
4964TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004965 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004966 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4967 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004968 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004969
4970 // Set focused application.
4971 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004972 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004973
4974 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004976 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004977 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004978
4979 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004980 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004982 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004983
4984 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004985 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004986 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004987 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004988 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004990 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004991 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004992
4993 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004994 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004996 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004997
4998 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004999 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00005000 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005001 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07005002 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005003 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005004 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00005005 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005006
5007 window->assertNoEvents();
5008}
5009
Gang Wange9087892020-01-07 12:17:14 -05005010TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005011 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005012 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5013 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05005014
5015 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005016 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05005017
Arthur Hung72d8dc32020-03-28 00:48:39 +00005018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005019 setFocusedWindow(window);
5020
Harry Cutts33476232023-01-30 19:57:29 +00005021 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05005022
5023 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5024 mDispatcher->notifyKey(&keyArgs);
5025
5026 InputEvent* event = window->consume();
5027 ASSERT_NE(event, nullptr);
5028
5029 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5030 ASSERT_NE(verified, nullptr);
5031 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
5032
5033 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
5034 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
5035 ASSERT_EQ(keyArgs.source, verified->source);
5036 ASSERT_EQ(keyArgs.displayId, verified->displayId);
5037
5038 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
5039
5040 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05005041 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005042 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05005043 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
5044 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
5045 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
5046 ASSERT_EQ(0, verifiedKey.repeatCount);
5047}
5048
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005049TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005051 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5052 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005053
5054 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5055
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005056 ui::Transform transform;
5057 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5058
5059 gui::DisplayInfo displayInfo;
5060 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
5061 displayInfo.transform = transform;
5062
5063 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005064
5065 NotifyMotionArgs motionArgs =
5066 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5067 ADISPLAY_ID_DEFAULT);
5068 mDispatcher->notifyMotion(&motionArgs);
5069
5070 InputEvent* event = window->consume();
5071 ASSERT_NE(event, nullptr);
5072
5073 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5074 ASSERT_NE(verified, nullptr);
5075 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
5076
5077 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
5078 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
5079 EXPECT_EQ(motionArgs.source, verified->source);
5080 EXPECT_EQ(motionArgs.displayId, verified->displayId);
5081
5082 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
5083
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005084 const vec2 rawXY =
5085 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
5086 motionArgs.pointerCoords[0].getXYValue());
5087 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
5088 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005089 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005090 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005091 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005092 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
5093 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
5094}
5095
chaviw09c8d2d2020-08-24 15:48:26 -07005096/**
5097 * Ensure that separate calls to sign the same data are generating the same key.
5098 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
5099 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
5100 * tests.
5101 */
5102TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
5103 KeyEvent event = getTestKeyEvent();
5104 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5105
5106 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
5107 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
5108 ASSERT_EQ(hmac1, hmac2);
5109}
5110
5111/**
5112 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
5113 */
5114TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
5115 KeyEvent event = getTestKeyEvent();
5116 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5117 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
5118
5119 verifiedEvent.deviceId += 1;
5120 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5121
5122 verifiedEvent.source += 1;
5123 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5124
5125 verifiedEvent.eventTimeNanos += 1;
5126 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5127
5128 verifiedEvent.displayId += 1;
5129 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5130
5131 verifiedEvent.action += 1;
5132 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5133
5134 verifiedEvent.downTimeNanos += 1;
5135 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5136
5137 verifiedEvent.flags += 1;
5138 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5139
5140 verifiedEvent.keyCode += 1;
5141 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5142
5143 verifiedEvent.scanCode += 1;
5144 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5145
5146 verifiedEvent.metaState += 1;
5147 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5148
5149 verifiedEvent.repeatCount += 1;
5150 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5151}
5152
Vishnu Nair958da932020-08-21 17:12:37 -07005153TEST_F(InputDispatcherTest, SetFocusedWindow) {
5154 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5155 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005156 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005157 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005158 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005159 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5160
5161 // Top window is also focusable but is not granted focus.
5162 windowTop->setFocusable(true);
5163 windowSecond->setFocusable(true);
5164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5165 setFocusedWindow(windowSecond);
5166
5167 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005168 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5169 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005170
5171 // Focused window should receive event.
5172 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5173 windowTop->assertNoEvents();
5174}
5175
5176TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5177 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5178 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005179 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005180 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5181
5182 window->setFocusable(true);
5183 // Release channel for window is no longer valid.
5184 window->releaseChannel();
5185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5186 setFocusedWindow(window);
5187
5188 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005189 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5190 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005191
5192 // window channel is invalid, so it should not receive any input event.
5193 window->assertNoEvents();
5194}
5195
5196TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5197 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5198 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005199 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005200 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005201 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5202
Vishnu Nair958da932020-08-21 17:12:37 -07005203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5204 setFocusedWindow(window);
5205
5206 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005207 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5208 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005209
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005210 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005211 window->assertNoEvents();
5212}
5213
5214TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5215 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5216 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005217 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005218 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005219 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005220 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5221
5222 windowTop->setFocusable(true);
5223 windowSecond->setFocusable(true);
5224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5225 setFocusedWindow(windowTop);
5226 windowTop->consumeFocusEvent(true);
5227
Chavi Weingarten847e8512023-03-29 00:26:09 +00005228 windowTop->editInfo()->focusTransferTarget = windowSecond->getToken();
5229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005230 windowSecond->consumeFocusEvent(true);
5231 windowTop->consumeFocusEvent(false);
5232
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5234 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005235
5236 // Focused window should receive event.
5237 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5238}
5239
Chavi Weingarten847e8512023-03-29 00:26:09 +00005240TEST_F(InputDispatcherTest, SetFocusedWindow_TransferFocusTokenNotFocusable) {
Vishnu Nair958da932020-08-21 17:12:37 -07005241 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5242 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005243 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005244 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005245 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005246 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5247
5248 windowTop->setFocusable(true);
Chavi Weingarten847e8512023-03-29 00:26:09 +00005249 windowSecond->setFocusable(false);
5250 windowTop->editInfo()->focusTransferTarget = windowSecond->getToken();
Vishnu Nair958da932020-08-21 17:12:37 -07005251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Chavi Weingarten847e8512023-03-29 00:26:09 +00005252 setFocusedWindow(windowTop);
5253 windowTop->consumeFocusEvent(true);
Vishnu Nair958da932020-08-21 17:12:37 -07005254
Chavi Weingarten847e8512023-03-29 00:26:09 +00005255 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5256 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005257
5258 // Event should be dropped.
Chavi Weingarten847e8512023-03-29 00:26:09 +00005259 windowTop->consumeKeyDown(ADISPLAY_ID_NONE);
Vishnu Nair958da932020-08-21 17:12:37 -07005260 windowSecond->assertNoEvents();
5261}
5262
5263TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5264 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5265 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005266 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005267 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005268 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5269 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005270 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5271
5272 window->setFocusable(true);
5273 previousFocusedWindow->setFocusable(true);
5274 window->setVisible(false);
5275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5276 setFocusedWindow(previousFocusedWindow);
5277 previousFocusedWindow->consumeFocusEvent(true);
5278
5279 // Requesting focus on invisible window takes focus from currently focused window.
5280 setFocusedWindow(window);
5281 previousFocusedWindow->consumeFocusEvent(false);
5282
5283 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005285 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5286 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005287
5288 // Window does not get focus event or key down.
5289 window->assertNoEvents();
5290
5291 // Window becomes visible.
5292 window->setVisible(true);
5293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5294
5295 // Window receives focus event.
5296 window->consumeFocusEvent(true);
5297 // Focused window receives key down.
5298 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5299}
5300
Vishnu Nair599f1412021-06-21 10:39:58 -07005301TEST_F(InputDispatcherTest, DisplayRemoved) {
5302 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5303 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005304 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005305 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5306
5307 // window is granted focus.
5308 window->setFocusable(true);
5309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5310 setFocusedWindow(window);
5311 window->consumeFocusEvent(true);
5312
5313 // When a display is removed window loses focus.
5314 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5315 window->consumeFocusEvent(false);
5316}
5317
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005318/**
5319 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5320 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5321 * of the 'slipperyEnterWindow'.
5322 *
5323 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5324 * a way so that the touched location is no longer covered by the top window.
5325 *
5326 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5327 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5328 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5329 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5330 * with ACTION_DOWN).
5331 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5332 * window moved itself away from the touched location and had Flag::SLIPPERY.
5333 *
5334 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5335 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5336 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5337 *
5338 * In this test, we ensure that the event received by the bottom window has
5339 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5340 */
5341TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005342 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5343 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005344
5345 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5346 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5347
5348 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005349 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005350 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005351 // Make sure this one overlaps the bottom window
5352 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5353 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5354 // one. Windows with the same owner are not considered to be occluding each other.
5355 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5356
5357 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005358 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005359 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5360
5361 mDispatcher->setInputWindows(
5362 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5363
5364 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5365 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5366 ADISPLAY_ID_DEFAULT, {{50, 50}});
5367 mDispatcher->notifyMotion(&args);
5368 slipperyExitWindow->consumeMotionDown();
5369 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5370 mDispatcher->setInputWindows(
5371 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5372
5373 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5374 ADISPLAY_ID_DEFAULT, {{51, 51}});
5375 mDispatcher->notifyMotion(&args);
5376
5377 slipperyExitWindow->consumeMotionCancel();
5378
5379 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5380 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5381}
5382
Garfield Tan1c7bc862020-01-28 13:24:04 -08005383class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5384protected:
5385 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5386 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5387
Chris Yea209fde2020-07-22 13:54:51 -07005388 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005389 sp<FakeWindowHandle> mWindow;
5390
5391 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005392 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005393 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005394 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005395 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5396 ASSERT_EQ(OK, mDispatcher->start());
5397
5398 setUpWindow();
5399 }
5400
5401 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005402 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005403 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005404
Vishnu Nair47074b82020-08-14 11:54:47 -07005405 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005406 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005407 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005408 mWindow->consumeFocusEvent(true);
5409 }
5410
Chris Ye2ad95392020-09-01 13:44:44 -07005411 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005412 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005413 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005414 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5415 mDispatcher->notifyKey(&keyArgs);
5416
5417 // Window should receive key down event.
5418 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5419 }
5420
5421 void expectKeyRepeatOnce(int32_t repeatCount) {
5422 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5423 InputEvent* repeatEvent = mWindow->consume();
5424 ASSERT_NE(nullptr, repeatEvent);
5425
5426 uint32_t eventType = repeatEvent->getType();
5427 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5428
5429 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5430 uint32_t eventAction = repeatKeyEvent->getAction();
5431 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5432 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5433 }
5434
Chris Ye2ad95392020-09-01 13:44:44 -07005435 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005436 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005437 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005438 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5439 mDispatcher->notifyKey(&keyArgs);
5440
5441 // Window should receive key down event.
5442 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005443 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005444 }
5445};
5446
5447TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005448 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005449 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5450 expectKeyRepeatOnce(repeatCount);
5451 }
5452}
5453
5454TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005455 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005456 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5457 expectKeyRepeatOnce(repeatCount);
5458 }
Harry Cutts33476232023-01-30 19:57:29 +00005459 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005460 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005461 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5462 expectKeyRepeatOnce(repeatCount);
5463 }
5464}
5465
5466TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005467 sendAndConsumeKeyDown(/*deviceId=*/1);
5468 expectKeyRepeatOnce(/*repeatCount=*/1);
5469 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005470 mWindow->assertNoEvents();
5471}
5472
5473TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005474 sendAndConsumeKeyDown(/*deviceId=*/1);
5475 expectKeyRepeatOnce(/*repeatCount=*/1);
5476 sendAndConsumeKeyDown(/*deviceId=*/2);
5477 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005478 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005479 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005480 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005481 expectKeyRepeatOnce(/*repeatCount=*/2);
5482 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005483 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005484 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005485 mWindow->assertNoEvents();
5486}
5487
5488TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005489 sendAndConsumeKeyDown(/*deviceId=*/1);
5490 expectKeyRepeatOnce(/*repeatCount=*/1);
5491 sendAndConsumeKeyDown(/*deviceId=*/2);
5492 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005493 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005494 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005495 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005496 mWindow->assertNoEvents();
5497}
5498
liushenxiang42232912021-05-21 20:24:09 +08005499TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5500 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005501 expectKeyRepeatOnce(/*repeatCount=*/1);
5502 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005503 mDispatcher->notifyDeviceReset(&args);
5504 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5505 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5506 mWindow->assertNoEvents();
5507}
5508
Garfield Tan1c7bc862020-01-28 13:24:04 -08005509TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005510 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005511 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005512 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5513 InputEvent* repeatEvent = mWindow->consume();
5514 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5515 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5516 IdGenerator::getSource(repeatEvent->getId()));
5517 }
5518}
5519
5520TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005521 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005522 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005523
5524 std::unordered_set<int32_t> idSet;
5525 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5526 InputEvent* repeatEvent = mWindow->consume();
5527 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5528 int32_t id = repeatEvent->getId();
5529 EXPECT_EQ(idSet.end(), idSet.find(id));
5530 idSet.insert(id);
5531 }
5532}
5533
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005534/* Test InputDispatcher for MultiDisplay */
5535class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5536public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005537 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005538 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005539
Chris Yea209fde2020-07-22 13:54:51 -07005540 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005541 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005542 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005543
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005544 // Set focus window for primary display, but focused display would be second one.
5545 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005546 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005548 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005549 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005550
Chris Yea209fde2020-07-22 13:54:51 -07005551 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005552 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005553 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005554 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005555 // Set focus display to second one.
5556 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5557 // Set focus window for second display.
5558 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005559 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005560 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005561 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005562 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005563 }
5564
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005565 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005566 InputDispatcherTest::TearDown();
5567
Chris Yea209fde2020-07-22 13:54:51 -07005568 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005569 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005570 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005571 windowInSecondary.clear();
5572 }
5573
5574protected:
Chris Yea209fde2020-07-22 13:54:51 -07005575 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005576 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005577 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005578 sp<FakeWindowHandle> windowInSecondary;
5579};
5580
5581TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5582 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005586 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005587 windowInSecondary->assertNoEvents();
5588
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005589 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5591 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005593 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005594 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005595}
5596
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005597TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005598 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5600 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005601 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005602 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005603 windowInSecondary->assertNoEvents();
5604
5605 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005608 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005609 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005610
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005611 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005612 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005613
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005614 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005615 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5616 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005617
5618 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005619 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005620 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005621 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005622 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005623 windowInSecondary->assertNoEvents();
5624}
5625
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005626// Test per-display input monitors for motion event.
5627TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005628 FakeMonitorReceiver monitorInPrimary =
5629 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5630 FakeMonitorReceiver monitorInSecondary =
5631 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005632
5633 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5635 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005637 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005638 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005639 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005640 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005641
5642 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5644 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5645 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005646 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005647 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005648 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005649 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005650
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08005651 // Lift up the touch from the second display
5652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5653 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5654 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5655 windowInSecondary->consumeMotionUp(SECOND_DISPLAY_ID);
5656 monitorInSecondary.consumeMotionUp(SECOND_DISPLAY_ID);
5657
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005658 // Test inject a non-pointer motion event.
5659 // If specific a display, it will dispatch to the focused window of particular display,
5660 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005664 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005665 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005666 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005667 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005668}
5669
5670// Test per-display input monitors for key event.
5671TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005672 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005673 FakeMonitorReceiver monitorInPrimary =
5674 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5675 FakeMonitorReceiver monitorInSecondary =
5676 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005677
5678 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5680 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005681 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005682 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005683 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005684 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005685}
5686
Vishnu Nair958da932020-08-21 17:12:37 -07005687TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5688 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005689 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005690 secondWindowInPrimary->setFocusable(true);
5691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5692 setFocusedWindow(secondWindowInPrimary);
5693 windowInPrimary->consumeFocusEvent(false);
5694 secondWindowInPrimary->consumeFocusEvent(true);
5695
5696 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5698 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005699 windowInPrimary->assertNoEvents();
5700 windowInSecondary->assertNoEvents();
5701 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5702}
5703
Arthur Hungdfd528e2021-12-08 13:23:04 +00005704TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5705 FakeMonitorReceiver monitorInPrimary =
5706 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5707 FakeMonitorReceiver monitorInSecondary =
5708 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5709
5710 // Test touch down on primary display.
5711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5714 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5715 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5716
5717 // Test touch down on second display.
5718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5721 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5722 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5723
5724 // Trigger cancel touch.
5725 mDispatcher->cancelCurrentTouch();
5726 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5727 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5728 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5729 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5730
5731 // Test inject a move motion event, no window/monitor should receive the event.
5732 ASSERT_EQ(InputEventInjectionResult::FAILED,
5733 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5734 ADISPLAY_ID_DEFAULT, {110, 200}))
5735 << "Inject motion event should return InputEventInjectionResult::FAILED";
5736 windowInPrimary->assertNoEvents();
5737 monitorInPrimary.assertNoEvents();
5738
5739 ASSERT_EQ(InputEventInjectionResult::FAILED,
5740 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5741 SECOND_DISPLAY_ID, {110, 200}))
5742 << "Inject motion event should return InputEventInjectionResult::FAILED";
5743 windowInSecondary->assertNoEvents();
5744 monitorInSecondary.assertNoEvents();
5745}
5746
Jackal Guof9696682018-10-05 12:23:23 +08005747class InputFilterTest : public InputDispatcherTest {
5748protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005749 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5750 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005751 NotifyMotionArgs motionArgs;
5752
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005753 motionArgs =
5754 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005755 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005756 motionArgs =
5757 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005758 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005759 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005760 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005761 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5762 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005763 } else {
5764 mFakePolicy->assertFilterInputEventWasNotCalled();
5765 }
5766 }
5767
5768 void testNotifyKey(bool expectToBeFiltered) {
5769 NotifyKeyArgs keyArgs;
5770
5771 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5772 mDispatcher->notifyKey(&keyArgs);
5773 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5774 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005775 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005776
5777 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005778 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005779 } else {
5780 mFakePolicy->assertFilterInputEventWasNotCalled();
5781 }
5782 }
5783};
5784
5785// Test InputFilter for MotionEvent
5786TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5787 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5788 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5789 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5790
5791 // Enable InputFilter
5792 mDispatcher->setInputFilterEnabled(true);
5793 // Test touch on both primary and second display, and check if both events are filtered.
5794 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5795 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5796
5797 // Disable InputFilter
5798 mDispatcher->setInputFilterEnabled(false);
5799 // Test touch on both primary and second display, and check if both events aren't filtered.
5800 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5801 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5802}
5803
5804// Test InputFilter for KeyEvent
5805TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5806 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5807 testNotifyKey(/*expectToBeFiltered*/ false);
5808
5809 // Enable InputFilter
5810 mDispatcher->setInputFilterEnabled(true);
5811 // Send a key event, and check if it is filtered.
5812 testNotifyKey(/*expectToBeFiltered*/ true);
5813
5814 // Disable InputFilter
5815 mDispatcher->setInputFilterEnabled(false);
5816 // Send a key event, and check if it isn't filtered.
5817 testNotifyKey(/*expectToBeFiltered*/ false);
5818}
5819
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005820// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5821// logical display coordinate space.
5822TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5823 ui::Transform firstDisplayTransform;
5824 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5825 ui::Transform secondDisplayTransform;
5826 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5827
5828 std::vector<gui::DisplayInfo> displayInfos(2);
5829 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5830 displayInfos[0].transform = firstDisplayTransform;
5831 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5832 displayInfos[1].transform = secondDisplayTransform;
5833
5834 mDispatcher->onWindowInfosChanged({}, displayInfos);
5835
5836 // Enable InputFilter
5837 mDispatcher->setInputFilterEnabled(true);
5838
5839 // Ensure the correct transforms are used for the displays.
5840 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5841 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5842}
5843
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005844class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5845protected:
5846 virtual void SetUp() override {
5847 InputDispatcherTest::SetUp();
5848
5849 /**
5850 * We don't need to enable input filter to test the injected event policy, but we enabled it
5851 * here to make the tests more realistic, since this policy only matters when inputfilter is
5852 * on.
5853 */
5854 mDispatcher->setInputFilterEnabled(true);
5855
5856 std::shared_ptr<InputApplicationHandle> application =
5857 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005858 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5859 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005860
5861 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5862 mWindow->setFocusable(true);
5863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5864 setFocusedWindow(mWindow);
5865 mWindow->consumeFocusEvent(true);
5866 }
5867
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005868 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5869 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005870 KeyEvent event;
5871
5872 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5873 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5874 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005875 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005876 const int32_t additionalPolicyFlags =
5877 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005879 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005880 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5881 policyFlags | additionalPolicyFlags));
5882
5883 InputEvent* received = mWindow->consume();
5884 ASSERT_NE(nullptr, received);
5885 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005886 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5887 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5888 ASSERT_EQ(flags, keyEvent.getFlags());
5889 }
5890
5891 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5892 int32_t flags) {
5893 MotionEvent event;
5894 PointerProperties pointerProperties[1];
5895 PointerCoords pointerCoords[1];
5896 pointerProperties[0].clear();
5897 pointerProperties[0].id = 0;
5898 pointerCoords[0].clear();
5899 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5900 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5901
5902 ui::Transform identityTransform;
5903 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5904 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5905 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5906 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5907 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005908 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005909 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005910 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5911
5912 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005914 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005915 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5916 policyFlags | additionalPolicyFlags));
5917
5918 InputEvent* received = mWindow->consume();
5919 ASSERT_NE(nullptr, received);
5920 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5921 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5922 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5923 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005924 }
5925
5926private:
5927 sp<FakeWindowHandle> mWindow;
5928};
5929
5930TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005931 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5932 // filter. Without it, the event will no different from a regularly injected event, and the
5933 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005934 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5935 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005936}
5937
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005938TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005939 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005940 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005941 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5942}
5943
5944TEST_F(InputFilterInjectionPolicyTest,
5945 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5946 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005947 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005948 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005949}
5950
5951TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005952 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5953 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005954}
5955
chaviwfd6d3512019-03-25 13:23:49 -07005956class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005957 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005958 InputDispatcherTest::SetUp();
5959
Chris Yea209fde2020-07-22 13:54:51 -07005960 std::shared_ptr<FakeApplicationHandle> application =
5961 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005962 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005963 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005964 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005965
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005966 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005967 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005968 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005969
5970 // Set focused application.
5971 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005972 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005973
5974 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005976 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005977 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005978 }
5979
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005980 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005981 InputDispatcherTest::TearDown();
5982
5983 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005984 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005985 }
5986
5987protected:
5988 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005989 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005990 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005991};
5992
5993// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5994// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5995// the onPointerDownOutsideFocus callback.
5996TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005998 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5999 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006000 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006001 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006002
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006003 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07006004 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
6005}
6006
6007// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
6008// DOWN on the window that doesn't have focus. Ensure no window received the
6009// onPointerDownOutsideFocus callback.
6010TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006012 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006013 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006014 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006015
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006016 ASSERT_TRUE(mDispatcher->waitForIdle());
6017 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006018}
6019
6020// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
6021// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
6022TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6024 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006025 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006026 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07006027
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006028 ASSERT_TRUE(mDispatcher->waitForIdle());
6029 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006030}
6031
6032// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
6033// DOWN on the window that already has focus. Ensure no window received the
6034// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10006035TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08006037 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006038 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006039 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006040 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006041
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006042 ASSERT_TRUE(mDispatcher->waitForIdle());
6043 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006044}
6045
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08006046// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
6047// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
6048TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
6049 const MotionEvent event =
6050 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6051 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07006052 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08006053 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
6054 .build();
6055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
6056 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6057 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
6058
6059 ASSERT_TRUE(mDispatcher->waitForIdle());
6060 mFakePolicy->assertOnPointerDownWasNotCalled();
6061 // Ensure that the unfocused window did not receive any FOCUS events.
6062 mUnfocusedWindow->assertNoEvents();
6063}
6064
chaviwaf87b3e2019-10-01 16:59:28 -07006065// These tests ensures we can send touch events to a single client when there are multiple input
6066// windows that point to the same client token.
6067class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
6068 virtual void SetUp() override {
6069 InputDispatcherTest::SetUp();
6070
Chris Yea209fde2020-07-22 13:54:51 -07006071 std::shared_ptr<FakeApplicationHandle> application =
6072 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006073 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
6074 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07006075 mWindow1->setFrame(Rect(0, 0, 100, 100));
6076
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006077 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
6078 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07006079 mWindow2->setFrame(Rect(100, 100, 200, 200));
6080
Arthur Hung72d8dc32020-03-28 00:48:39 +00006081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07006082 }
6083
6084protected:
6085 sp<FakeWindowHandle> mWindow1;
6086 sp<FakeWindowHandle> mWindow2;
6087
6088 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05006089 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07006090 vec2 vals = windowInfo->transform.transform(point.x, point.y);
6091 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07006092 }
6093
6094 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
6095 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01006096 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07006097 InputEvent* event = window->consume();
6098
6099 ASSERT_NE(nullptr, event) << name.c_str()
6100 << ": consumer should have returned non-NULL event.";
6101
6102 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
6103 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
6104 << " event, got " << inputEventTypeToString(event->getType()) << " event";
6105
6106 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00006107 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08006108 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07006109
6110 for (size_t i = 0; i < points.size(); i++) {
6111 float expectedX = points[i].x;
6112 float expectedY = points[i].y;
6113
6114 EXPECT_EQ(expectedX, motionEvent.getX(i))
6115 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
6116 << ", got " << motionEvent.getX(i);
6117 EXPECT_EQ(expectedY, motionEvent.getY(i))
6118 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
6119 << ", got " << motionEvent.getY(i);
6120 }
6121 }
chaviw9eaa22c2020-07-01 16:21:27 -07006122
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08006123 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07006124 std::vector<PointF> expectedPoints) {
6125 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
6126 ADISPLAY_ID_DEFAULT, touchedPoints);
6127 mDispatcher->notifyMotion(&motionArgs);
6128
6129 // Always consume from window1 since it's the window that has the InputReceiver
6130 consumeMotionEvent(mWindow1, action, expectedPoints);
6131 }
chaviwaf87b3e2019-10-01 16:59:28 -07006132};
6133
6134TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
6135 // Touch Window 1
6136 PointF touchedPoint = {10, 10};
6137 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006138 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006139
6140 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006141 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006142
6143 // Touch Window 2
6144 touchedPoint = {150, 150};
6145 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006146 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006147}
6148
chaviw9eaa22c2020-07-01 16:21:27 -07006149TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
6150 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07006151 mWindow2->setWindowScale(0.5f, 0.5f);
6152
6153 // Touch Window 1
6154 PointF touchedPoint = {10, 10};
6155 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006156 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006157 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006158 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006159
6160 // Touch Window 2
6161 touchedPoint = {150, 150};
6162 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006163 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
6164 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006165
chaviw9eaa22c2020-07-01 16:21:27 -07006166 // Update the transform so rotation is set
6167 mWindow2->setWindowTransform(0, -1, 1, 0);
6168 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
6169 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006170}
6171
chaviw9eaa22c2020-07-01 16:21:27 -07006172TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006173 mWindow2->setWindowScale(0.5f, 0.5f);
6174
6175 // Touch Window 1
6176 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6177 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006178 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006179
6180 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006181 touchedPoints.push_back(PointF{150, 150});
6182 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006183 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006184
chaviw9eaa22c2020-07-01 16:21:27 -07006185 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006186 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006187 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006188
chaviw9eaa22c2020-07-01 16:21:27 -07006189 // Update the transform so rotation is set for Window 2
6190 mWindow2->setWindowTransform(0, -1, 1, 0);
6191 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006192 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006193}
6194
chaviw9eaa22c2020-07-01 16:21:27 -07006195TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006196 mWindow2->setWindowScale(0.5f, 0.5f);
6197
6198 // Touch Window 1
6199 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6200 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006201 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006202
6203 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006204 touchedPoints.push_back(PointF{150, 150});
6205 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006206
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006207 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006208
6209 // Move both windows
6210 touchedPoints = {{20, 20}, {175, 175}};
6211 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6212 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6213
chaviw9eaa22c2020-07-01 16:21:27 -07006214 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006215
chaviw9eaa22c2020-07-01 16:21:27 -07006216 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006217 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006218 expectedPoints.pop_back();
6219
6220 // Touch Window 2
6221 mWindow2->setWindowTransform(0, -1, 1, 0);
6222 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006223 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006224
6225 // Move both windows
6226 touchedPoints = {{20, 20}, {175, 175}};
6227 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6228 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6229
6230 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006231}
6232
6233TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6234 mWindow1->setWindowScale(0.5f, 0.5f);
6235
6236 // Touch Window 1
6237 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6238 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006239 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006240
6241 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006242 touchedPoints.push_back(PointF{150, 150});
6243 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006244
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006245 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006246
6247 // Move both windows
6248 touchedPoints = {{20, 20}, {175, 175}};
6249 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6250 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6251
chaviw9eaa22c2020-07-01 16:21:27 -07006252 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006253}
6254
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006255class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6256 virtual void SetUp() override {
6257 InputDispatcherTest::SetUp();
6258
Chris Yea209fde2020-07-22 13:54:51 -07006259 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006260 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006261 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6262 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006263 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006264 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006265 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006266
6267 // Set focused application.
6268 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6269
6270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006271 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006272 mWindow->consumeFocusEvent(true);
6273 }
6274
6275 virtual void TearDown() override {
6276 InputDispatcherTest::TearDown();
6277 mWindow.clear();
6278 }
6279
6280protected:
Chris Yea209fde2020-07-22 13:54:51 -07006281 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006282 sp<FakeWindowHandle> mWindow;
6283 static constexpr PointF WINDOW_LOCATION = {20, 20};
6284
6285 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006287 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6288 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006290 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6291 WINDOW_LOCATION));
6292 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006293
6294 sp<FakeWindowHandle> addSpyWindow() {
6295 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006296 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006297 spy->setTrustedOverlay(true);
6298 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006299 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006300 spy->setDispatchingTimeout(30ms);
6301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6302 return spy;
6303 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006304};
6305
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006306// Send a tap and respond, which should not cause an ANR.
6307TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6308 tapOnWindow();
6309 mWindow->consumeMotionDown();
6310 mWindow->consumeMotionUp();
6311 ASSERT_TRUE(mDispatcher->waitForIdle());
6312 mFakePolicy->assertNotifyAnrWasNotCalled();
6313}
6314
6315// Send a regular key and respond, which should not cause an ANR.
6316TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006318 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6319 ASSERT_TRUE(mDispatcher->waitForIdle());
6320 mFakePolicy->assertNotifyAnrWasNotCalled();
6321}
6322
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006323TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6324 mWindow->setFocusable(false);
6325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6326 mWindow->consumeFocusEvent(false);
6327
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006328 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006329 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6330 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6331 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006333 // Key will not go to window because we have no focused window.
6334 // The 'no focused window' ANR timer should start instead.
6335
6336 // Now, the focused application goes away.
6337 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6338 // The key should get dropped and there should be no ANR.
6339
6340 ASSERT_TRUE(mDispatcher->waitForIdle());
6341 mFakePolicy->assertNotifyAnrWasNotCalled();
6342}
6343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006344// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006345// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6346// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006347TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006348 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006349 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6350 WINDOW_LOCATION));
6351
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006352 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6353 ASSERT_TRUE(sequenceNum);
6354 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006355 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006356
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006357 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006358 mWindow->consumeMotionEvent(
6359 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006360 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006361 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006362}
6363
6364// Send a key to the app and have the app not respond right away.
6365TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6366 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006368 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6369 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006370 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006371 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006372 ASSERT_TRUE(mDispatcher->waitForIdle());
6373}
6374
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006375// We have a focused application, but no focused window
6376TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006377 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6379 mWindow->consumeFocusEvent(false);
6380
6381 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6384 WINDOW_LOCATION));
6385 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6386 mDispatcher->waitForIdle();
6387 mFakePolicy->assertNotifyAnrWasNotCalled();
6388
6389 // Once a focused event arrives, we get an ANR for this application
6390 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6391 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006392 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006393 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6394 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006395 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006396 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006397 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006398 ASSERT_TRUE(mDispatcher->waitForIdle());
6399}
6400
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006401/**
6402 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6403 * there will not be an ANR.
6404 */
6405TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6406 mWindow->setFocusable(false);
6407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6408 mWindow->consumeFocusEvent(false);
6409
6410 KeyEvent event;
6411 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6412 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6413
6414 // Define a valid key down event that is stale (too old).
6415 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6416 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006417 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006418
6419 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6420
6421 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006422 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006423 InputEventInjectionSync::WAIT_FOR_RESULT,
6424 INJECT_EVENT_TIMEOUT, policyFlags);
6425 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6426 << "Injection should fail because the event is stale";
6427
6428 ASSERT_TRUE(mDispatcher->waitForIdle());
6429 mFakePolicy->assertNotifyAnrWasNotCalled();
6430 mWindow->assertNoEvents();
6431}
6432
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006433// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006434// Make sure that we don't notify policy twice about the same ANR.
6435TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006436 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6438 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006439
6440 // Once a focused event arrives, we get an ANR for this application
6441 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6442 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006443 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006444 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6445 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006446 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006447 const std::chrono::duration appTimeout =
6448 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6449 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006450
Vishnu Naire4df8752022-09-08 09:17:55 -07006451 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006452 // ANR should not be raised again. It is up to policy to do that if it desires.
6453 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006454
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006455 // If we now get a focused window, the ANR should stop, but the policy handles that via
6456 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006457 ASSERT_TRUE(mDispatcher->waitForIdle());
6458}
6459
6460// We have a focused application, but no focused window
6461TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006462 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6464 mWindow->consumeFocusEvent(false);
6465
6466 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006467 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006468 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006469 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6470 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006471
Vishnu Naire4df8752022-09-08 09:17:55 -07006472 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6473 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006474
6475 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006476 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006477 ASSERT_TRUE(mDispatcher->waitForIdle());
6478 mWindow->assertNoEvents();
6479}
6480
6481/**
6482 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6483 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6484 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6485 * the ANR mechanism should still work.
6486 *
6487 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6488 * DOWN event, while not responding on the second one.
6489 */
6490TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6491 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6492 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6493 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6494 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6495 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006496 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006497
6498 // Now send ACTION_UP, with identical timestamp
6499 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6500 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6501 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6502 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006503 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006504
6505 // We have now sent down and up. Let's consume first event and then ANR on the second.
6506 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6507 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006508 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006509}
6510
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006511// A spy window can receive an ANR
6512TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6513 sp<FakeWindowHandle> spy = addSpyWindow();
6514
6515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6517 WINDOW_LOCATION));
6518 mWindow->consumeMotionDown();
6519
6520 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6521 ASSERT_TRUE(sequenceNum);
6522 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006523 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006524
6525 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006526 spy->consumeMotionEvent(
6527 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006528 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006529 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006530}
6531
6532// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006533// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006534TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6535 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006536
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6538 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006539 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006540 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006541
6542 // Stuck on the ACTION_UP
6543 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006544 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006545
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006546 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006547 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006548 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6549 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006550
6551 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6552 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006553 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006554 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006555 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006556}
6557
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006558// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006559// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006560TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6561 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006562
6563 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006564 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6565 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006566
6567 mWindow->consumeMotionDown();
6568 // Stuck on the ACTION_UP
6569 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006570 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006571
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006572 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006573 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006574 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6575 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006576
6577 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6578 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006579 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006580 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006581 spy->assertNoEvents();
6582}
6583
6584TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6585 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6586
6587 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6588
6589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6591 WINDOW_LOCATION));
6592
6593 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6594 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6595 ASSERT_TRUE(consumeSeq);
6596
Prabir Pradhanedd96402022-02-15 01:46:16 -08006597 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006598
6599 monitor.finishEvent(*consumeSeq);
6600 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6601
6602 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006603 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006604}
6605
6606// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6607// process events, you don't get an anr. When the window later becomes unresponsive again, you
6608// get an ANR again.
6609// 1. tap -> block on ACTION_UP -> receive ANR
6610// 2. consume all pending events (= queue becomes healthy again)
6611// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6612TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6613 tapOnWindow();
6614
6615 mWindow->consumeMotionDown();
6616 // Block on ACTION_UP
6617 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006618 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006619 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6620 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006621 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006622 mWindow->assertNoEvents();
6623
6624 tapOnWindow();
6625 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006626 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006627 mWindow->consumeMotionUp();
6628
6629 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006630 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006631 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006632 mWindow->assertNoEvents();
6633}
6634
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006635// If a connection remains unresponsive for a while, make sure policy is only notified once about
6636// it.
6637TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006639 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6640 WINDOW_LOCATION));
6641
6642 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006643 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006644 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006645 // 'notifyConnectionUnresponsive' should only be called once per connection
6646 mFakePolicy->assertNotifyAnrWasNotCalled();
6647 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006648 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006649 mWindow->consumeMotionEvent(
6650 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006651 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006652 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006653 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006654 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006655}
6656
6657/**
6658 * If a window is processing a motion event, and then a key event comes in, the key event should
6659 * not to to the focused window until the motion is processed.
6660 *
6661 * Warning!!!
6662 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6663 * and the injection timeout that we specify when injecting the key.
6664 * We must have the injection timeout (10ms) be smaller than
6665 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6666 *
6667 * If that value changes, this test should also change.
6668 */
6669TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6670 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6672
6673 tapOnWindow();
6674 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6675 ASSERT_TRUE(downSequenceNum);
6676 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6677 ASSERT_TRUE(upSequenceNum);
6678 // Don't finish the events yet, and send a key
6679 // Injection will "succeed" because we will eventually give up and send the key to the focused
6680 // window even if motions are still being processed. But because the injection timeout is short,
6681 // we will receive INJECTION_TIMED_OUT as the result.
6682
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006683 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006684 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006685 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6686 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006687 // Key will not be sent to the window, yet, because the window is still processing events
6688 // and the key remains pending, waiting for the touch events to be processed
6689 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6690 ASSERT_FALSE(keySequenceNum);
6691
6692 std::this_thread::sleep_for(500ms);
6693 // if we wait long enough though, dispatcher will give up, and still send the key
6694 // to the focused window, even though we have not yet finished the motion event
6695 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6696 mWindow->finishEvent(*downSequenceNum);
6697 mWindow->finishEvent(*upSequenceNum);
6698}
6699
6700/**
6701 * If a window is processing a motion event, and then a key event comes in, the key event should
6702 * not go to the focused window until the motion is processed.
6703 * If then a new motion comes in, then the pending key event should be going to the currently
6704 * focused window right away.
6705 */
6706TEST_F(InputDispatcherSingleWindowAnr,
6707 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6708 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6710
6711 tapOnWindow();
6712 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6713 ASSERT_TRUE(downSequenceNum);
6714 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6715 ASSERT_TRUE(upSequenceNum);
6716 // Don't finish the events yet, and send a key
6717 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006719 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6720 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006721 // At this point, key is still pending, and should not be sent to the application yet.
6722 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6723 ASSERT_FALSE(keySequenceNum);
6724
6725 // Now tap down again. It should cause the pending key to go to the focused window right away.
6726 tapOnWindow();
6727 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6728 // the other events yet. We can finish events in any order.
6729 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6730 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6731 mWindow->consumeMotionDown();
6732 mWindow->consumeMotionUp();
6733 mWindow->assertNoEvents();
6734}
6735
6736class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6737 virtual void SetUp() override {
6738 InputDispatcherTest::SetUp();
6739
Chris Yea209fde2020-07-22 13:54:51 -07006740 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006741 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006742 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6743 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006744 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006745 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006746 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006747
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006748 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6749 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006750 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006751 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006752
6753 // Set focused application.
6754 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006755 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006756
6757 // Expect one focus window exist in display.
6758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006759 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006760 mFocusedWindow->consumeFocusEvent(true);
6761 }
6762
6763 virtual void TearDown() override {
6764 InputDispatcherTest::TearDown();
6765
6766 mUnfocusedWindow.clear();
6767 mFocusedWindow.clear();
6768 }
6769
6770protected:
Chris Yea209fde2020-07-22 13:54:51 -07006771 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006772 sp<FakeWindowHandle> mUnfocusedWindow;
6773 sp<FakeWindowHandle> mFocusedWindow;
6774 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6775 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6776 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6777
6778 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6779
6780 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6781
6782private:
6783 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006785 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6786 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006788 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6789 location));
6790 }
6791};
6792
6793// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6794// should be ANR'd first.
6795TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006797 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6798 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006800 mFocusedWindow->consumeMotionDown();
6801 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006802 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006803 // We consumed all events, so no ANR
6804 ASSERT_TRUE(mDispatcher->waitForIdle());
6805 mFakePolicy->assertNotifyAnrWasNotCalled();
6806
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006808 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6809 FOCUSED_WINDOW_LOCATION));
6810 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6811 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006812
6813 const std::chrono::duration timeout =
6814 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006815 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006816 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6817 // sequence to make it consistent
6818 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006819 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006820 mFocusedWindow->consumeMotionDown();
6821 // This cancel is generated because the connection was unresponsive
6822 mFocusedWindow->consumeMotionCancel();
6823 mFocusedWindow->assertNoEvents();
6824 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006825 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006826 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6827 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006828 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006829}
6830
6831// If we have 2 windows with identical timeouts that are both unresponsive,
6832// it doesn't matter which order they should have ANR.
6833// But we should receive ANR for both.
6834TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6835 // Set the timeout for unfocused window to match the focused window
6836 mUnfocusedWindow->setDispatchingTimeout(10ms);
6837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6838
6839 tapOnFocusedWindow();
6840 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006841 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6842 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6843 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006844
6845 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006846 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6847 mFocusedWindow->getToken() == anrConnectionToken2);
6848 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6849 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006850
6851 ASSERT_TRUE(mDispatcher->waitForIdle());
6852 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006853
6854 mFocusedWindow->consumeMotionDown();
6855 mFocusedWindow->consumeMotionUp();
6856 mUnfocusedWindow->consumeMotionOutside();
6857
Prabir Pradhanedd96402022-02-15 01:46:16 -08006858 sp<IBinder> responsiveToken1, responsiveToken2;
6859 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6860 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006861
6862 // Both applications should be marked as responsive, in any order
6863 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6864 mFocusedWindow->getToken() == responsiveToken2);
6865 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6866 mUnfocusedWindow->getToken() == responsiveToken2);
6867 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006868}
6869
6870// If a window is already not responding, the second tap on the same window should be ignored.
6871// We should also log an error to account for the dropped event (not tested here).
6872// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6873TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6874 tapOnFocusedWindow();
6875 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006876 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006877 // Receive the events, but don't respond
6878 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6879 ASSERT_TRUE(downEventSequenceNum);
6880 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6881 ASSERT_TRUE(upEventSequenceNum);
6882 const std::chrono::duration timeout =
6883 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006884 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006885
6886 // Tap once again
6887 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006888 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006889 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6890 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006891 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006892 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6893 FOCUSED_WINDOW_LOCATION));
6894 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6895 // valid touch target
6896 mUnfocusedWindow->assertNoEvents();
6897
6898 // Consume the first tap
6899 mFocusedWindow->finishEvent(*downEventSequenceNum);
6900 mFocusedWindow->finishEvent(*upEventSequenceNum);
6901 ASSERT_TRUE(mDispatcher->waitForIdle());
6902 // The second tap did not go to the focused window
6903 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006904 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006905 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6906 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006907 mFakePolicy->assertNotifyAnrWasNotCalled();
6908}
6909
6910// If you tap outside of all windows, there will not be ANR
6911TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006912 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006913 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6914 LOCATION_OUTSIDE_ALL_WINDOWS));
6915 ASSERT_TRUE(mDispatcher->waitForIdle());
6916 mFakePolicy->assertNotifyAnrWasNotCalled();
6917}
6918
6919// Since the focused window is paused, tapping on it should not produce any events
6920TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6921 mFocusedWindow->setPaused(true);
6922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6923
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006924 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6926 FOCUSED_WINDOW_LOCATION));
6927
6928 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6929 ASSERT_TRUE(mDispatcher->waitForIdle());
6930 // Should not ANR because the window is paused, and touches shouldn't go to it
6931 mFakePolicy->assertNotifyAnrWasNotCalled();
6932
6933 mFocusedWindow->assertNoEvents();
6934 mUnfocusedWindow->assertNoEvents();
6935}
6936
6937/**
6938 * If a window is processing a motion event, and then a key event comes in, the key event should
6939 * not to to the focused window until the motion is processed.
6940 * If a different window becomes focused at this time, the key should go to that window instead.
6941 *
6942 * Warning!!!
6943 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6944 * and the injection timeout that we specify when injecting the key.
6945 * We must have the injection timeout (10ms) be smaller than
6946 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6947 *
6948 * If that value changes, this test should also change.
6949 */
6950TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6951 // Set a long ANR timeout to prevent it from triggering
6952 mFocusedWindow->setDispatchingTimeout(2s);
6953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6954
6955 tapOnUnfocusedWindow();
6956 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6957 ASSERT_TRUE(downSequenceNum);
6958 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6959 ASSERT_TRUE(upSequenceNum);
6960 // Don't finish the events yet, and send a key
6961 // Injection will succeed because we will eventually give up and send the key to the focused
6962 // window even if motions are still being processed.
6963
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006964 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006965 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6966 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006968 // Key will not be sent to the window, yet, because the window is still processing events
6969 // and the key remains pending, waiting for the touch events to be processed
6970 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6971 ASSERT_FALSE(keySequenceNum);
6972
6973 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006974 mFocusedWindow->setFocusable(false);
6975 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006977 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006978
6979 // Focus events should precede the key events
6980 mUnfocusedWindow->consumeFocusEvent(true);
6981 mFocusedWindow->consumeFocusEvent(false);
6982
6983 // Finish the tap events, which should unblock dispatcher
6984 mUnfocusedWindow->finishEvent(*downSequenceNum);
6985 mUnfocusedWindow->finishEvent(*upSequenceNum);
6986
6987 // Now that all queues are cleared and no backlog in the connections, the key event
6988 // can finally go to the newly focused "mUnfocusedWindow".
6989 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6990 mFocusedWindow->assertNoEvents();
6991 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006992 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006993}
6994
6995// When the touch stream is split across 2 windows, and one of them does not respond,
6996// then ANR should be raised and the touch should be canceled for the unresponsive window.
6997// The other window should not be affected by that.
6998TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6999 // Touch Window 1
7000 NotifyMotionArgs motionArgs =
7001 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7002 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
7003 mDispatcher->notifyMotion(&motionArgs);
7004 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00007005 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007006
7007 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007008 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7009 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007010 mDispatcher->notifyMotion(&motionArgs);
7011
7012 const std::chrono::duration timeout =
7013 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08007014 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007015
7016 mUnfocusedWindow->consumeMotionDown();
7017 mFocusedWindow->consumeMotionDown();
7018 // Focused window may or may not receive ACTION_MOVE
7019 // But it should definitely receive ACTION_CANCEL due to the ANR
7020 InputEvent* event;
7021 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
7022 ASSERT_TRUE(moveOrCancelSequenceNum);
7023 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
7024 ASSERT_NE(nullptr, event);
7025 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
7026 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
7027 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
7028 mFocusedWindow->consumeMotionCancel();
7029 } else {
7030 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
7031 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007032 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08007033 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
7034 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05007035
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007036 mUnfocusedWindow->assertNoEvents();
7037 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05007038 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007039}
7040
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007041/**
7042 * If we have no focused window, and a key comes in, we start the ANR timer.
7043 * The focused application should add a focused window before the timer runs out to prevent ANR.
7044 *
7045 * If the user touches another application during this time, the key should be dropped.
7046 * Next, if a new focused window comes in, without toggling the focused application,
7047 * then no ANR should occur.
7048 *
7049 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
7050 * but in some cases the policy may not update the focused application.
7051 */
7052TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
7053 std::shared_ptr<FakeApplicationHandle> focusedApplication =
7054 std::make_shared<FakeApplicationHandle>();
7055 focusedApplication->setDispatchingTimeout(60ms);
7056 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
7057 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
7058 mFocusedWindow->setFocusable(false);
7059
7060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7061 mFocusedWindow->consumeFocusEvent(false);
7062
7063 // Send a key. The ANR timer should start because there is no focused window.
7064 // 'focusedApplication' will get blamed if this timer completes.
7065 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007066 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00007067 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7068 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
7069 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007071
7072 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
7073 // then the injected touches won't cause the focused event to get dropped.
7074 // The dispatcher only checks for whether the queue should be pruned upon queueing.
7075 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
7076 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
7077 // For this test, it means that the key would get delivered to the window once it becomes
7078 // focused.
7079 std::this_thread::sleep_for(10ms);
7080
7081 // Touch unfocused window. This should force the pending key to get dropped.
7082 NotifyMotionArgs motionArgs =
7083 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7084 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
7085 mDispatcher->notifyMotion(&motionArgs);
7086
7087 // We do not consume the motion right away, because that would require dispatcher to first
7088 // process (== drop) the key event, and by that time, ANR will be raised.
7089 // Set the focused window first.
7090 mFocusedWindow->setFocusable(true);
7091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7092 setFocusedWindow(mFocusedWindow);
7093 mFocusedWindow->consumeFocusEvent(true);
7094 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
7095 // to another application. This could be a bug / behaviour in the policy.
7096
7097 mUnfocusedWindow->consumeMotionDown();
7098
7099 ASSERT_TRUE(mDispatcher->waitForIdle());
7100 // Should not ANR because we actually have a focused window. It was just added too slowly.
7101 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
7102}
7103
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007104// These tests ensure we cannot send touch events to a window that's positioned behind a window
7105// that has feature NO_INPUT_CHANNEL.
7106// Layout:
7107// Top (closest to user)
7108// mNoInputWindow (above all windows)
7109// mBottomWindow
7110// Bottom (furthest from user)
7111class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
7112 virtual void SetUp() override {
7113 InputDispatcherTest::SetUp();
7114
7115 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007116 mNoInputWindow =
7117 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7118 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00007119 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007120 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007121 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7122 // It's perfectly valid for this window to not have an associated input channel
7123
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007124 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
7125 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007126 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
7127
7128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7129 }
7130
7131protected:
7132 std::shared_ptr<FakeApplicationHandle> mApplication;
7133 sp<FakeWindowHandle> mNoInputWindow;
7134 sp<FakeWindowHandle> mBottomWindow;
7135};
7136
7137TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
7138 PointF touchedPoint = {10, 10};
7139
7140 NotifyMotionArgs motionArgs =
7141 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7142 ADISPLAY_ID_DEFAULT, {touchedPoint});
7143 mDispatcher->notifyMotion(&motionArgs);
7144
7145 mNoInputWindow->assertNoEvents();
7146 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
7147 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
7148 // and therefore should prevent mBottomWindow from receiving touches
7149 mBottomWindow->assertNoEvents();
7150}
7151
7152/**
7153 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
7154 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
7155 */
7156TEST_F(InputDispatcherMultiWindowOcclusionTests,
7157 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007158 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7159 "Window with input channel and NO_INPUT_CHANNEL",
7160 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007161
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007162 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007163 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7165
7166 PointF touchedPoint = {10, 10};
7167
7168 NotifyMotionArgs motionArgs =
7169 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7170 ADISPLAY_ID_DEFAULT, {touchedPoint});
7171 mDispatcher->notifyMotion(&motionArgs);
7172
7173 mNoInputWindow->assertNoEvents();
7174 mBottomWindow->assertNoEvents();
7175}
7176
Vishnu Nair958da932020-08-21 17:12:37 -07007177class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7178protected:
7179 std::shared_ptr<FakeApplicationHandle> mApp;
7180 sp<FakeWindowHandle> mWindow;
7181 sp<FakeWindowHandle> mMirror;
7182
7183 virtual void SetUp() override {
7184 InputDispatcherTest::SetUp();
7185 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007186 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7187 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7188 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007189 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7190 mWindow->setFocusable(true);
7191 mMirror->setFocusable(true);
7192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7193 }
7194};
7195
7196TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7197 // Request focus on a mirrored window
7198 setFocusedWindow(mMirror);
7199
7200 // window gets focused
7201 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7203 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007204 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7205}
7206
7207// A focused & mirrored window remains focused only if the window and its mirror are both
7208// focusable.
7209TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7210 setFocusedWindow(mMirror);
7211
7212 // window gets focused
7213 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7215 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007216 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007217 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7218 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007219 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7220
7221 mMirror->setFocusable(false);
7222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7223
7224 // window loses focus since one of the windows associated with the token in not focusable
7225 mWindow->consumeFocusEvent(false);
7226
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007227 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7228 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007229 mWindow->assertNoEvents();
7230}
7231
7232// A focused & mirrored window remains focused until the window and its mirror both become
7233// invisible.
7234TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7235 setFocusedWindow(mMirror);
7236
7237 // window gets focused
7238 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7240 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007241 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7243 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007244 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7245
7246 mMirror->setVisible(false);
7247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7248
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7250 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007251 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7253 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007254 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7255
7256 mWindow->setVisible(false);
7257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7258
7259 // window loses focus only after all windows associated with the token become invisible.
7260 mWindow->consumeFocusEvent(false);
7261
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007262 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7263 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007264 mWindow->assertNoEvents();
7265}
7266
7267// A focused & mirrored window remains focused until both windows are removed.
7268TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7269 setFocusedWindow(mMirror);
7270
7271 // window gets focused
7272 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007273 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7274 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007275 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7277 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007278 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7279
7280 // single window is removed but the window token remains focused
7281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7282
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007283 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7284 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007285 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7287 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007288 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7289
7290 // Both windows are removed
7291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7292 mWindow->consumeFocusEvent(false);
7293
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007294 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7295 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007296 mWindow->assertNoEvents();
7297}
7298
7299// Focus request can be pending until one window becomes visible.
7300TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7301 // Request focus on an invisible mirror.
7302 mWindow->setVisible(false);
7303 mMirror->setVisible(false);
7304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7305 setFocusedWindow(mMirror);
7306
7307 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007309 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7310 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007311
7312 mMirror->setVisible(true);
7313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7314
7315 // window gets focused
7316 mWindow->consumeFocusEvent(true);
7317 // window gets the pending key event
7318 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7319}
Prabir Pradhan99987712020-11-10 18:43:05 -08007320
7321class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7322protected:
7323 std::shared_ptr<FakeApplicationHandle> mApp;
7324 sp<FakeWindowHandle> mWindow;
7325 sp<FakeWindowHandle> mSecondWindow;
7326
7327 void SetUp() override {
7328 InputDispatcherTest::SetUp();
7329 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007330 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007331 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007332 mSecondWindow =
7333 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007334 mSecondWindow->setFocusable(true);
7335
7336 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7338
7339 setFocusedWindow(mWindow);
7340 mWindow->consumeFocusEvent(true);
7341 }
7342
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007343 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7344 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007345 mDispatcher->notifyPointerCaptureChanged(&args);
7346 }
7347
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007348 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7349 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007350 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007351 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7352 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007353 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007354 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007355 }
7356};
7357
7358TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7359 // Ensure that capture cannot be obtained for unfocused windows.
7360 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7361 mFakePolicy->assertSetPointerCaptureNotCalled();
7362 mSecondWindow->assertNoEvents();
7363
7364 // Ensure that capture can be enabled from the focus window.
7365 requestAndVerifyPointerCapture(mWindow, true);
7366
7367 // Ensure that capture cannot be disabled from a window that does not have capture.
7368 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7369 mFakePolicy->assertSetPointerCaptureNotCalled();
7370
7371 // Ensure that capture can be disabled from the window with capture.
7372 requestAndVerifyPointerCapture(mWindow, false);
7373}
7374
7375TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007376 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007377
7378 setFocusedWindow(mSecondWindow);
7379
7380 // Ensure that the capture disabled event was sent first.
7381 mWindow->consumeCaptureEvent(false);
7382 mWindow->consumeFocusEvent(false);
7383 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007384 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007385
7386 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007387 notifyPointerCaptureChanged({});
7388 notifyPointerCaptureChanged(request);
7389 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007390 mWindow->assertNoEvents();
7391 mSecondWindow->assertNoEvents();
7392 mFakePolicy->assertSetPointerCaptureNotCalled();
7393}
7394
7395TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007396 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007397
7398 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007399 notifyPointerCaptureChanged({});
7400 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007401
7402 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007403 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007404 mWindow->consumeCaptureEvent(false);
7405 mWindow->assertNoEvents();
7406}
7407
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007408TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7409 requestAndVerifyPointerCapture(mWindow, true);
7410
7411 // The first window loses focus.
7412 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007413 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007414 mWindow->consumeCaptureEvent(false);
7415
7416 // Request Pointer Capture from the second window before the notification from InputReader
7417 // arrives.
7418 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007419 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007420
7421 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007422 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007423
7424 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007425 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007426
7427 mSecondWindow->consumeFocusEvent(true);
7428 mSecondWindow->consumeCaptureEvent(true);
7429}
7430
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007431TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7432 // App repeatedly enables and disables capture.
7433 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7434 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7435 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7436 mFakePolicy->assertSetPointerCaptureCalled(false);
7437 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7438 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7439
7440 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7441 // first request is now stale, this should do nothing.
7442 notifyPointerCaptureChanged(firstRequest);
7443 mWindow->assertNoEvents();
7444
7445 // InputReader notifies that the second request was enabled.
7446 notifyPointerCaptureChanged(secondRequest);
7447 mWindow->consumeCaptureEvent(true);
7448}
7449
Prabir Pradhan7092e262022-05-03 16:51:09 +00007450TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7451 requestAndVerifyPointerCapture(mWindow, true);
7452
7453 // App toggles pointer capture off and on.
7454 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7455 mFakePolicy->assertSetPointerCaptureCalled(false);
7456
7457 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7458 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7459
7460 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7461 // preceding "disable" request.
7462 notifyPointerCaptureChanged(enableRequest);
7463
7464 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7465 // any notifications.
7466 mWindow->assertNoEvents();
7467}
7468
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007469class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7470protected:
7471 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007472
7473 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7474 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7475
7476 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7477 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7478
7479 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7480 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7481 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7482 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7483 MAXIMUM_OBSCURING_OPACITY);
7484
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007485 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007486 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007487 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007488
7489 sp<FakeWindowHandle> mTouchWindow;
7490
7491 virtual void SetUp() override {
7492 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007493 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007494 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7495 }
7496
7497 virtual void TearDown() override {
7498 InputDispatcherTest::TearDown();
7499 mTouchWindow.clear();
7500 }
7501
chaviw3277faf2021-05-19 16:45:23 -05007502 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7503 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007504 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007505 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007506 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007507 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007508 return window;
7509 }
7510
7511 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7512 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7513 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007514 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007515 // Generate an arbitrary PID based on the UID
7516 window->setOwnerInfo(1777 + (uid % 10000), uid);
7517 return window;
7518 }
7519
7520 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7521 NotifyMotionArgs args =
7522 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7523 ADISPLAY_ID_DEFAULT, points);
7524 mDispatcher->notifyMotion(&args);
7525 }
7526};
7527
7528TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007529 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007530 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007532
7533 touch();
7534
7535 mTouchWindow->assertNoEvents();
7536}
7537
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007538TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007539 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7540 const sp<FakeWindowHandle>& w =
7541 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7543
7544 touch();
7545
7546 mTouchWindow->assertNoEvents();
7547}
7548
7549TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007550 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7551 const sp<FakeWindowHandle>& w =
7552 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7554
7555 touch();
7556
7557 w->assertNoEvents();
7558}
7559
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007560TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007561 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007563
7564 touch();
7565
7566 mTouchWindow->consumeAnyMotionDown();
7567}
7568
7569TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007570 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007571 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007572 w->setFrame(Rect(0, 0, 50, 50));
7573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007574
7575 touch({PointF{100, 100}});
7576
7577 mTouchWindow->consumeAnyMotionDown();
7578}
7579
7580TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007581 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007582 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7584
7585 touch();
7586
7587 mTouchWindow->consumeAnyMotionDown();
7588}
7589
7590TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7591 const sp<FakeWindowHandle>& w =
7592 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007594
7595 touch();
7596
7597 mTouchWindow->consumeAnyMotionDown();
7598}
7599
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007600TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7601 const sp<FakeWindowHandle>& w =
7602 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7604
7605 touch();
7606
7607 w->assertNoEvents();
7608}
7609
7610/**
7611 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7612 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7613 * window, the occluding window will still receive ACTION_OUTSIDE event.
7614 */
7615TEST_F(InputDispatcherUntrustedTouchesTest,
7616 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7617 const sp<FakeWindowHandle>& w =
7618 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007619 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7621
7622 touch();
7623
7624 w->consumeMotionOutside();
7625}
7626
7627TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7628 const sp<FakeWindowHandle>& w =
7629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007630 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7632
7633 touch();
7634
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007635 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007636}
7637
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007638TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007639 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007640 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7641 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7643
7644 touch();
7645
7646 mTouchWindow->consumeAnyMotionDown();
7647}
7648
7649TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7650 const sp<FakeWindowHandle>& w =
7651 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7652 MAXIMUM_OBSCURING_OPACITY);
7653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007654
7655 touch();
7656
7657 mTouchWindow->consumeAnyMotionDown();
7658}
7659
7660TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007661 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007662 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7663 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7665
7666 touch();
7667
7668 mTouchWindow->assertNoEvents();
7669}
7670
7671TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7672 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7673 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007674 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7675 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007676 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007677 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7678 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7680
7681 touch();
7682
7683 mTouchWindow->assertNoEvents();
7684}
7685
7686TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7687 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7688 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007689 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7690 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007691 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007692 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7693 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7695
7696 touch();
7697
7698 mTouchWindow->consumeAnyMotionDown();
7699}
7700
7701TEST_F(InputDispatcherUntrustedTouchesTest,
7702 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7703 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007704 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7705 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007706 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007707 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7708 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7710
7711 touch();
7712
7713 mTouchWindow->consumeAnyMotionDown();
7714}
7715
7716TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7717 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007718 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7719 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007720 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007721 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7722 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007724
7725 touch();
7726
7727 mTouchWindow->assertNoEvents();
7728}
7729
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007730TEST_F(InputDispatcherUntrustedTouchesTest,
7731 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7732 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007733 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7734 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007735 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007736 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7737 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7739
7740 touch();
7741
7742 mTouchWindow->assertNoEvents();
7743}
7744
7745TEST_F(InputDispatcherUntrustedTouchesTest,
7746 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7747 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007748 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7749 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007750 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007751 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7752 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7754
7755 touch();
7756
7757 mTouchWindow->consumeAnyMotionDown();
7758}
7759
7760TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7761 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007762 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7763 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7765
7766 touch();
7767
7768 mTouchWindow->consumeAnyMotionDown();
7769}
7770
7771TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7772 const sp<FakeWindowHandle>& w =
7773 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7775
7776 touch();
7777
7778 mTouchWindow->consumeAnyMotionDown();
7779}
7780
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007781TEST_F(InputDispatcherUntrustedTouchesTest,
7782 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7783 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7784 const sp<FakeWindowHandle>& w =
7785 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7787
7788 touch();
7789
7790 mTouchWindow->assertNoEvents();
7791}
7792
7793TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7794 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7795 const sp<FakeWindowHandle>& w =
7796 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7798
7799 touch();
7800
7801 mTouchWindow->consumeAnyMotionDown();
7802}
7803
7804TEST_F(InputDispatcherUntrustedTouchesTest,
7805 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7806 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7807 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007808 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7809 OPACITY_ABOVE_THRESHOLD);
7810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7811
7812 touch();
7813
7814 mTouchWindow->consumeAnyMotionDown();
7815}
7816
7817TEST_F(InputDispatcherUntrustedTouchesTest,
7818 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7819 const sp<FakeWindowHandle>& w1 =
7820 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7821 OPACITY_BELOW_THRESHOLD);
7822 const sp<FakeWindowHandle>& w2 =
7823 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7824 OPACITY_BELOW_THRESHOLD);
7825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7826
7827 touch();
7828
7829 mTouchWindow->assertNoEvents();
7830}
7831
7832/**
7833 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7834 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7835 * (which alone would result in allowing touches) does not affect the blocking behavior.
7836 */
7837TEST_F(InputDispatcherUntrustedTouchesTest,
7838 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7839 const sp<FakeWindowHandle>& wB =
7840 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7841 OPACITY_BELOW_THRESHOLD);
7842 const sp<FakeWindowHandle>& wC =
7843 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7844 OPACITY_BELOW_THRESHOLD);
7845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7846
7847 touch();
7848
7849 mTouchWindow->assertNoEvents();
7850}
7851
7852/**
7853 * This test is testing that a window from a different UID but with same application token doesn't
7854 * block the touch. Apps can share the application token for close UI collaboration for example.
7855 */
7856TEST_F(InputDispatcherUntrustedTouchesTest,
7857 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7858 const sp<FakeWindowHandle>& w =
7859 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7860 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7862
7863 touch();
7864
7865 mTouchWindow->consumeAnyMotionDown();
7866}
7867
arthurhungb89ccb02020-12-30 16:19:01 +08007868class InputDispatcherDragTests : public InputDispatcherTest {
7869protected:
7870 std::shared_ptr<FakeApplicationHandle> mApp;
7871 sp<FakeWindowHandle> mWindow;
7872 sp<FakeWindowHandle> mSecondWindow;
7873 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007874 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007875 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7876 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007877
7878 void SetUp() override {
7879 InputDispatcherTest::SetUp();
7880 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007881 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007882 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007883
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007884 mSecondWindow =
7885 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007886 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007887
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007888 mSpyWindow =
7889 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007890 mSpyWindow->setSpy(true);
7891 mSpyWindow->setTrustedOverlay(true);
7892 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7893
arthurhungb89ccb02020-12-30 16:19:01 +08007894 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007896 }
7897
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007898 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7899 switch (fromSource) {
7900 case AINPUT_SOURCE_TOUCHSCREEN:
7901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7903 ADISPLAY_ID_DEFAULT, {50, 50}))
7904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7905 break;
7906 case AINPUT_SOURCE_STYLUS:
7907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7908 injectMotionEvent(
7909 mDispatcher,
7910 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7911 AINPUT_SOURCE_STYLUS)
7912 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07007913 .pointer(PointerBuilder(0, ToolType::STYLUS)
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007914 .x(50)
7915 .y(50))
7916 .build()));
7917 break;
7918 case AINPUT_SOURCE_MOUSE:
7919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7920 injectMotionEvent(
7921 mDispatcher,
7922 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7923 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7924 .pointer(PointerBuilder(MOUSE_POINTER_ID,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07007925 ToolType::MOUSE)
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007926 .x(50)
7927 .y(50))
7928 .build()));
7929 break;
7930 default:
7931 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7932 }
arthurhungb89ccb02020-12-30 16:19:01 +08007933
7934 // Window should receive motion event.
7935 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007936 // Spy window should also receive motion event
7937 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007938 }
7939
7940 // Start performing drag, we will create a drag window and transfer touch to it.
7941 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7942 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007943 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007944 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007945 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007946 }
arthurhungb89ccb02020-12-30 16:19:01 +08007947
7948 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007949 mDragWindow =
7950 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007951 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007952 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007953 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007954
7955 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007956 bool transferred =
7957 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007958 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007959 if (transferred) {
7960 mWindow->consumeMotionCancel();
7961 mDragWindow->consumeMotionDown();
7962 }
7963 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007964 }
7965};
7966
7967TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007968 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007969
7970 // Move on window.
7971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7972 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7973 ADISPLAY_ID_DEFAULT, {50, 50}))
7974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7975 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7976 mWindow->consumeDragEvent(false, 50, 50);
7977 mSecondWindow->assertNoEvents();
7978
7979 // Move to another window.
7980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7981 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7982 ADISPLAY_ID_DEFAULT, {150, 50}))
7983 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7984 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7985 mWindow->consumeDragEvent(true, 150, 50);
7986 mSecondWindow->consumeDragEvent(false, 50, 50);
7987
7988 // Move back to original window.
7989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7990 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7991 ADISPLAY_ID_DEFAULT, {50, 50}))
7992 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7993 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7994 mWindow->consumeDragEvent(false, 50, 50);
7995 mSecondWindow->consumeDragEvent(true, -50, 50);
7996
7997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7998 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7999 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8000 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8001 mWindow->assertNoEvents();
8002 mSecondWindow->assertNoEvents();
8003}
8004
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008005TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008006 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008007
8008 // No cancel event after drag start
8009 mSpyWindow->assertNoEvents();
8010
8011 const MotionEvent secondFingerDownEvent =
8012 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8013 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008014 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(50).y(50))
8015 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008016 .build();
8017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8018 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8019 InputEventInjectionSync::WAIT_FOR_RESULT))
8020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8021
8022 // Receives cancel for first pointer after next pointer down
8023 mSpyWindow->consumeMotionCancel();
8024 mSpyWindow->consumeMotionDown();
8025
8026 mSpyWindow->assertNoEvents();
8027}
8028
arthurhungf452d0b2021-01-06 00:19:52 +08008029TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008030 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08008031
8032 // Move on window.
8033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8034 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8035 ADISPLAY_ID_DEFAULT, {50, 50}))
8036 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8037 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8038 mWindow->consumeDragEvent(false, 50, 50);
8039 mSecondWindow->assertNoEvents();
8040
8041 // Move to another window.
8042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8043 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8044 ADISPLAY_ID_DEFAULT, {150, 50}))
8045 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8046 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8047 mWindow->consumeDragEvent(true, 150, 50);
8048 mSecondWindow->consumeDragEvent(false, 50, 50);
8049
8050 // drop to another window.
8051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8052 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8053 {150, 50}))
8054 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8055 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8056 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8057 mWindow->assertNoEvents();
8058 mSecondWindow->assertNoEvents();
8059}
8060
arthurhung6d4bed92021-03-17 11:59:33 +08008061TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008062 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08008063
8064 // Move on window and keep button pressed.
8065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8066 injectMotionEvent(mDispatcher,
8067 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8068 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008069 .pointer(PointerBuilder(0, ToolType::STYLUS).x(50).y(50))
arthurhung6d4bed92021-03-17 11:59:33 +08008070 .build()))
8071 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8072 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8073 mWindow->consumeDragEvent(false, 50, 50);
8074 mSecondWindow->assertNoEvents();
8075
8076 // Move to another window and release button, expect to drop item.
8077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8078 injectMotionEvent(mDispatcher,
8079 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8080 .buttonState(0)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008081 .pointer(PointerBuilder(0, ToolType::STYLUS).x(150).y(50))
arthurhung6d4bed92021-03-17 11:59:33 +08008082 .build()))
8083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8084 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8085 mWindow->assertNoEvents();
8086 mSecondWindow->assertNoEvents();
8087 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8088
8089 // nothing to the window.
8090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8091 injectMotionEvent(mDispatcher,
8092 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
8093 .buttonState(0)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008094 .pointer(PointerBuilder(0, ToolType::STYLUS).x(150).y(50))
arthurhung6d4bed92021-03-17 11:59:33 +08008095 .build()))
8096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8097 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8098 mWindow->assertNoEvents();
8099 mSecondWindow->assertNoEvents();
8100}
8101
Arthur Hung54745652022-04-20 07:17:41 +00008102TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008103 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08008104
8105 // Set second window invisible.
8106 mSecondWindow->setVisible(false);
8107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
8108
8109 // Move on window.
8110 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8111 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8112 ADISPLAY_ID_DEFAULT, {50, 50}))
8113 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8114 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8115 mWindow->consumeDragEvent(false, 50, 50);
8116 mSecondWindow->assertNoEvents();
8117
8118 // Move to another window.
8119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8120 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8121 ADISPLAY_ID_DEFAULT, {150, 50}))
8122 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8123 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8124 mWindow->consumeDragEvent(true, 150, 50);
8125 mSecondWindow->assertNoEvents();
8126
8127 // drop to another window.
8128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8129 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8130 {150, 50}))
8131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8132 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8133 mFakePolicy->assertDropTargetEquals(nullptr);
8134 mWindow->assertNoEvents();
8135 mSecondWindow->assertNoEvents();
8136}
8137
Arthur Hung54745652022-04-20 07:17:41 +00008138TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008139 // Ensure window could track pointerIds if it didn't support split touch.
8140 mWindow->setPreventSplitting(true);
8141
Arthur Hung54745652022-04-20 07:17:41 +00008142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8143 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8144 {50, 50}))
8145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8146 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8147
8148 const MotionEvent secondFingerDownEvent =
8149 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8150 .displayId(ADISPLAY_ID_DEFAULT)
8151 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008152 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(50).y(50))
8153 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008154 .build();
8155 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8156 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8157 InputEventInjectionSync::WAIT_FOR_RESULT))
8158 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008159 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00008160
8161 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008162 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008163}
8164
8165TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
8166 // First down on second window.
8167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8168 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8169 {150, 50}))
8170 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8171
8172 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8173
8174 // Second down on first window.
8175 const MotionEvent secondFingerDownEvent =
8176 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8177 .displayId(ADISPLAY_ID_DEFAULT)
8178 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008179 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(150).y(50))
8180 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008181 .build();
8182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8183 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8184 InputEventInjectionSync::WAIT_FOR_RESULT))
8185 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8186 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8187
8188 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008189 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008190
8191 // Move on window.
8192 const MotionEvent secondFingerMoveEvent =
8193 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8194 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008195 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(150).y(50))
8196 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008197 .build();
8198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8199 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8200 InputEventInjectionSync::WAIT_FOR_RESULT));
8201 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8202 mWindow->consumeDragEvent(false, 50, 50);
8203 mSecondWindow->consumeMotionMove();
8204
8205 // Release the drag pointer should perform drop.
8206 const MotionEvent secondFingerUpEvent =
8207 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8208 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008209 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(150).y(50))
8210 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008211 .build();
8212 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8213 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8214 InputEventInjectionSync::WAIT_FOR_RESULT));
8215 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8216 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8217 mWindow->assertNoEvents();
8218 mSecondWindow->consumeMotionMove();
8219}
8220
Arthur Hung3915c1f2022-05-31 07:17:17 +00008221TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008222 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008223
8224 // Update window of second display.
8225 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008226 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008227 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8228
8229 // Let second display has a touch state.
8230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8231 injectMotionEvent(mDispatcher,
8232 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8233 AINPUT_SOURCE_TOUCHSCREEN)
8234 .displayId(SECOND_DISPLAY_ID)
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008235 .pointer(PointerBuilder(0, ToolType::FINGER).x(100).y(100))
Arthur Hung3915c1f2022-05-31 07:17:17 +00008236 .build()));
8237 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008238 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008239 // Update window again.
8240 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8241
8242 // Move on window.
8243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8244 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8245 ADISPLAY_ID_DEFAULT, {50, 50}))
8246 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8247 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8248 mWindow->consumeDragEvent(false, 50, 50);
8249 mSecondWindow->assertNoEvents();
8250
8251 // Move to another window.
8252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8253 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8254 ADISPLAY_ID_DEFAULT, {150, 50}))
8255 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8256 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8257 mWindow->consumeDragEvent(true, 150, 50);
8258 mSecondWindow->consumeDragEvent(false, 50, 50);
8259
8260 // drop to another window.
8261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8262 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8263 {150, 50}))
8264 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8265 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8266 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8267 mWindow->assertNoEvents();
8268 mSecondWindow->assertNoEvents();
8269}
8270
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008271TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8272 startDrag(true, AINPUT_SOURCE_MOUSE);
8273 // Move on window.
8274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8275 injectMotionEvent(mDispatcher,
8276 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8277 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8278 .pointer(PointerBuilder(MOUSE_POINTER_ID,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008279 ToolType::MOUSE)
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008280 .x(50)
8281 .y(50))
8282 .build()))
8283 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8284 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8285 mWindow->consumeDragEvent(false, 50, 50);
8286 mSecondWindow->assertNoEvents();
8287
8288 // Move to another window.
8289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8290 injectMotionEvent(mDispatcher,
8291 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8292 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8293 .pointer(PointerBuilder(MOUSE_POINTER_ID,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008294 ToolType::MOUSE)
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008295 .x(150)
8296 .y(50))
8297 .build()))
8298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8299 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8300 mWindow->consumeDragEvent(true, 150, 50);
8301 mSecondWindow->consumeDragEvent(false, 50, 50);
8302
8303 // drop to another window.
8304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8305 injectMotionEvent(mDispatcher,
8306 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8307 .buttonState(0)
8308 .pointer(PointerBuilder(MOUSE_POINTER_ID,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008309 ToolType::MOUSE)
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008310 .x(150)
8311 .y(50))
8312 .build()))
8313 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8314 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8315 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8316 mWindow->assertNoEvents();
8317 mSecondWindow->assertNoEvents();
8318}
8319
Vishnu Nair062a8672021-09-03 16:07:44 -07008320class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8321
8322TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8323 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008324 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8325 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008326 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008327 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8328 window->setFocusable(true);
8329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8330 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008331 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008332
8333 // With the flag set, window should not get any input
8334 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8335 mDispatcher->notifyKey(&keyArgs);
8336 window->assertNoEvents();
8337
8338 NotifyMotionArgs motionArgs =
8339 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8340 ADISPLAY_ID_DEFAULT);
8341 mDispatcher->notifyMotion(&motionArgs);
8342 window->assertNoEvents();
8343
8344 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008345 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8347
8348 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8349 mDispatcher->notifyKey(&keyArgs);
8350 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8351
8352 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8353 ADISPLAY_ID_DEFAULT);
8354 mDispatcher->notifyMotion(&motionArgs);
8355 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8356 window->assertNoEvents();
8357}
8358
8359TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8360 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8361 std::make_shared<FakeApplicationHandle>();
8362 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008363 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8364 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008365 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8366 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008367 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008368 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008369 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8370 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008371 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008372 window->setOwnerInfo(222, 222);
8373 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8374 window->setFocusable(true);
8375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8376 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008377 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008378
8379 // With the flag set, window should not get any input
8380 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8381 mDispatcher->notifyKey(&keyArgs);
8382 window->assertNoEvents();
8383
8384 NotifyMotionArgs motionArgs =
8385 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8386 ADISPLAY_ID_DEFAULT);
8387 mDispatcher->notifyMotion(&motionArgs);
8388 window->assertNoEvents();
8389
8390 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008391 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8393
8394 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8395 mDispatcher->notifyKey(&keyArgs);
8396 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8397
8398 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8399 ADISPLAY_ID_DEFAULT);
8400 mDispatcher->notifyMotion(&motionArgs);
8401 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8402 window->assertNoEvents();
8403}
8404
8405TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8406 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8407 std::make_shared<FakeApplicationHandle>();
8408 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008409 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8410 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008411 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8412 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008413 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008415 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8416 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008417 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008418 window->setOwnerInfo(222, 222);
8419 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8420 window->setFocusable(true);
8421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8422 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008423 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008424
8425 // With the flag set, window should not get any input
8426 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8427 mDispatcher->notifyKey(&keyArgs);
8428 window->assertNoEvents();
8429
8430 NotifyMotionArgs motionArgs =
8431 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8432 ADISPLAY_ID_DEFAULT);
8433 mDispatcher->notifyMotion(&motionArgs);
8434 window->assertNoEvents();
8435
8436 // When the window is no longer obscured because it went on top, it should get input
8437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8438
8439 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8440 mDispatcher->notifyKey(&keyArgs);
8441 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8442
8443 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8444 ADISPLAY_ID_DEFAULT);
8445 mDispatcher->notifyMotion(&motionArgs);
8446 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8447 window->assertNoEvents();
8448}
8449
Antonio Kantekf16f2832021-09-28 04:39:20 +00008450class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8451protected:
8452 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008453 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008454 sp<FakeWindowHandle> mWindow;
8455 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008456 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008457
8458 void SetUp() override {
8459 InputDispatcherTest::SetUp();
8460
8461 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008462 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008463 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008464 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008465 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008466 mSecondWindow =
8467 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008468 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008469 mThirdWindow =
8470 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8471 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8472 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008473
8474 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8476 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8477 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008478 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008479
Antonio Kantek15beb512022-06-13 22:35:41 +00008480 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008481 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008482 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008483 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8484 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008485 mThirdWindow->assertNoEvents();
8486 }
8487
8488 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8489 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008490 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008491 SECOND_DISPLAY_ID)) {
8492 mWindow->assertNoEvents();
8493 mSecondWindow->assertNoEvents();
8494 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008495 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008496 }
8497
Antonio Kantek15beb512022-06-13 22:35:41 +00008498 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8499 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008500 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8501 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008502 mWindow->consumeTouchModeEvent(inTouchMode);
8503 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008504 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008505 }
8506};
8507
Antonio Kantek26defcf2022-02-08 01:12:27 +00008508TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008509 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008510 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8511 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008512 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008513}
8514
Antonio Kantek26defcf2022-02-08 01:12:27 +00008515TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8516 const WindowInfo& windowInfo = *mWindow->getInfo();
8517 int32_t ownerPid = windowInfo.ownerPid;
8518 int32_t ownerUid = windowInfo.ownerUid;
8519 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8520 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008521 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008522 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008523 mWindow->assertNoEvents();
8524 mSecondWindow->assertNoEvents();
8525}
8526
8527TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8528 const WindowInfo& windowInfo = *mWindow->getInfo();
8529 int32_t ownerPid = windowInfo.ownerPid;
8530 int32_t ownerUid = windowInfo.ownerUid;
8531 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008532 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008533 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008534}
8535
Antonio Kantekf16f2832021-09-28 04:39:20 +00008536TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008537 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008538 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8539 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008540 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008541 mWindow->assertNoEvents();
8542 mSecondWindow->assertNoEvents();
8543}
8544
Antonio Kantek15beb512022-06-13 22:35:41 +00008545TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8546 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8547 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8548 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008549 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008550 mWindow->assertNoEvents();
8551 mSecondWindow->assertNoEvents();
8552 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8553}
8554
Antonio Kantek48710e42022-03-24 14:19:30 -07008555TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8556 // Interact with the window first.
8557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8558 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8559 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8560
8561 // Then remove focus.
8562 mWindow->setFocusable(false);
8563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8564
8565 // Assert that caller can switch touch mode by owning one of the last interacted window.
8566 const WindowInfo& windowInfo = *mWindow->getInfo();
8567 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8568 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008569 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008570}
8571
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008572class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8573public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008574 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008575 std::shared_ptr<FakeApplicationHandle> application =
8576 std::make_shared<FakeApplicationHandle>();
8577 std::string name = "Fake Spy ";
8578 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008579 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8580 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008581 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008582 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008583 return spy;
8584 }
8585
8586 sp<FakeWindowHandle> createForeground() {
8587 std::shared_ptr<FakeApplicationHandle> application =
8588 std::make_shared<FakeApplicationHandle>();
8589 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008590 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8591 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008592 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008593 return window;
8594 }
8595
8596private:
8597 int mSpyCount{0};
8598};
8599
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008600using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008601/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008602 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8603 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008604TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8605 ScopedSilentDeath _silentDeath;
8606
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008607 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008608 spy->setTrustedOverlay(false);
8609 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8610 ".* not a trusted overlay");
8611}
8612
8613/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008614 * Input injection into a display with a spy window but no foreground windows should succeed.
8615 */
8616TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008617 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008618 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8619
8620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8621 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8622 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8623 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8624}
8625
8626/**
8627 * Verify the order in which different input windows receive events. The touched foreground window
8628 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8629 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8630 * receive events before ones belows it.
8631 *
8632 * Here, we set up a scenario with four windows in the following Z order from the top:
8633 * spy1, spy2, window, spy3.
8634 * We then inject an event and verify that the foreground "window" receives it first, followed by
8635 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8636 * window.
8637 */
8638TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8639 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008640 auto spy1 = createSpy();
8641 auto spy2 = createSpy();
8642 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8644 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8645 const size_t numChannels = channels.size();
8646
Michael Wright8e9a8562022-02-09 13:44:29 +00008647 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008648 if (!epollFd.ok()) {
8649 FAIL() << "Failed to create epoll fd";
8650 }
8651
8652 for (size_t i = 0; i < numChannels; i++) {
8653 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8654 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8655 FAIL() << "Failed to add fd to epoll";
8656 }
8657 }
8658
8659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8662
8663 std::vector<size_t> eventOrder;
8664 std::vector<struct epoll_event> events(numChannels);
8665 for (;;) {
8666 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8667 (100ms).count());
8668 if (nFds < 0) {
8669 FAIL() << "Failed to call epoll_wait";
8670 }
8671 if (nFds == 0) {
8672 break; // epoll_wait timed out
8673 }
8674 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008675 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008676 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008677 channels[i]->consumeMotionDown();
8678 }
8679 }
8680
8681 // Verify the order in which the events were received.
8682 EXPECT_EQ(3u, eventOrder.size());
8683 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8684 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8685 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8686}
8687
8688/**
8689 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8690 */
8691TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8692 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008693 auto spy = createSpy();
8694 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8696
8697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8699 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8700 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8701 spy->assertNoEvents();
8702}
8703
8704/**
8705 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8706 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8707 * to the window.
8708 */
8709TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8710 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008711 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008712 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8714
8715 // Inject an event outside the spy window's touchable region.
8716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8717 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8718 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8719 window->consumeMotionDown();
8720 spy->assertNoEvents();
8721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8722 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8723 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8724 window->consumeMotionUp();
8725 spy->assertNoEvents();
8726
8727 // Inject an event inside the spy window's touchable region.
8728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8729 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8730 {5, 10}))
8731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8732 window->consumeMotionDown();
8733 spy->consumeMotionDown();
8734}
8735
8736/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008737 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008738 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008739 */
8740TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8741 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008742 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008743 auto spy = createSpy();
8744 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008745 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008746 spy->setFrame(Rect{0, 0, 20, 20});
8747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8748
8749 // Inject an event outside the spy window's frame and touchable region.
8750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008751 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8752 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8754 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008755 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008756}
8757
8758/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008759 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8760 * pointers that are down within its bounds.
8761 */
8762TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8763 auto windowLeft = createForeground();
8764 windowLeft->setFrame({0, 0, 100, 200});
8765 auto windowRight = createForeground();
8766 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008767 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008768 spy->setFrame({0, 0, 200, 200});
8769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8770
8771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8772 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8773 {50, 50}))
8774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8775 windowLeft->consumeMotionDown();
8776 spy->consumeMotionDown();
8777
8778 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008779 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008780 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008781 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(50).y(50))
8782 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008783 .build();
8784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8785 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8786 InputEventInjectionSync::WAIT_FOR_RESULT))
8787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8788 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008789 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008790}
8791
8792/**
8793 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8794 * the spy should receive the second pointer with ACTION_DOWN.
8795 */
8796TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8797 auto window = createForeground();
8798 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008799 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008800 spyRight->setFrame({100, 0, 200, 200});
8801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8802
8803 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8804 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8805 {50, 50}))
8806 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8807 window->consumeMotionDown();
8808 spyRight->assertNoEvents();
8809
8810 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008811 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008812 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008813 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(50).y(50))
8814 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008815 .build();
8816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8817 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8818 InputEventInjectionSync::WAIT_FOR_RESULT))
8819 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008820 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008821 spyRight->consumeMotionDown();
8822}
8823
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008824/**
8825 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8826 * windows should be allowed to control split touch.
8827 */
8828TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008829 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008830 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008831 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008832 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008833
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008834 auto window = createForeground();
8835 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008836
8837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8838
8839 // First finger down, no window touched.
8840 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8841 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8842 {100, 200}))
8843 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8844 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8845 window->assertNoEvents();
8846
8847 // Second finger down on window, the window should receive touch down.
8848 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008849 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008850 .displayId(ADISPLAY_ID_DEFAULT)
8851 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008852 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(200))
8853 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008854 .build();
8855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8856 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8857 InputEventInjectionSync::WAIT_FOR_RESULT))
8858 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8859
8860 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008861 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008862}
8863
8864/**
8865 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8866 * do not receive key events.
8867 */
8868TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008869 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008870 spy->setFocusable(false);
8871
8872 auto window = createForeground();
8873 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8874 setFocusedWindow(window);
8875 window->consumeFocusEvent(true);
8876
8877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8878 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8879 window->consumeKeyDown(ADISPLAY_ID_NONE);
8880
8881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8882 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8883 window->consumeKeyUp(ADISPLAY_ID_NONE);
8884
8885 spy->assertNoEvents();
8886}
8887
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008888using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8889
8890/**
8891 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8892 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8893 */
8894TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8895 auto window = createForeground();
8896 auto spy1 = createSpy();
8897 auto spy2 = createSpy();
8898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8899
8900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8903 window->consumeMotionDown();
8904 spy1->consumeMotionDown();
8905 spy2->consumeMotionDown();
8906
8907 // Pilfer pointers from the second spy window.
8908 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8909 spy2->assertNoEvents();
8910 spy1->consumeMotionCancel();
8911 window->consumeMotionCancel();
8912
8913 // The rest of the gesture should only be sent to the second spy window.
8914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8915 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8916 ADISPLAY_ID_DEFAULT))
8917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8918 spy2->consumeMotionMove();
8919 spy1->assertNoEvents();
8920 window->assertNoEvents();
8921}
8922
8923/**
8924 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8925 * in the middle of the gesture.
8926 */
8927TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8928 auto window = createForeground();
8929 auto spy = createSpy();
8930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8931
8932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8933 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8935 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8936 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8937
8938 window->releaseChannel();
8939
8940 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8941
8942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8943 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8945 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8946}
8947
8948/**
8949 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8950 * the spy, but not to any other windows.
8951 */
8952TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8953 auto spy = createSpy();
8954 auto window = createForeground();
8955
8956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8957
8958 // First finger down on the window and the spy.
8959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8961 {100, 200}))
8962 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8963 spy->consumeMotionDown();
8964 window->consumeMotionDown();
8965
8966 // Spy window pilfers the pointers.
8967 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8968 window->consumeMotionCancel();
8969
8970 // Second finger down on the window and spy, but the window should not receive the pointer down.
8971 const MotionEvent secondFingerDownEvent =
8972 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8973 .displayId(ADISPLAY_ID_DEFAULT)
8974 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008975 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(200))
8976 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008977 .build();
8978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8979 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8980 InputEventInjectionSync::WAIT_FOR_RESULT))
8981 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8982
Harry Cutts33476232023-01-30 19:57:29 +00008983 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008984
8985 // Third finger goes down outside all windows, so injection should fail.
8986 const MotionEvent thirdFingerDownEvent =
8987 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8988 .displayId(ADISPLAY_ID_DEFAULT)
8989 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07008990 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(100).y(200))
8991 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
8992 .pointer(PointerBuilder(/*id=*/2, ToolType::FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008993 .build();
8994 ASSERT_EQ(InputEventInjectionResult::FAILED,
8995 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8996 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008997 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008998
8999 spy->assertNoEvents();
9000 window->assertNoEvents();
9001}
9002
9003/**
9004 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
9005 */
9006TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
9007 auto spy = createSpy();
9008 spy->setFrame(Rect(0, 0, 100, 100));
9009 auto window = createForeground();
9010 window->setFrame(Rect(0, 0, 200, 200));
9011
9012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9013
9014 // First finger down on the window only
9015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9017 {150, 150}))
9018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9019 window->consumeMotionDown();
9020
9021 // Second finger down on the spy and window
9022 const MotionEvent secondFingerDownEvent =
9023 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9024 .displayId(ADISPLAY_ID_DEFAULT)
9025 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07009026 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(150).y(150))
9027 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009028 .build();
9029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9030 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9031 InputEventInjectionSync::WAIT_FOR_RESULT))
9032 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9033 spy->consumeMotionDown();
9034 window->consumeMotionPointerDown(1);
9035
9036 // Third finger down on the spy and window
9037 const MotionEvent thirdFingerDownEvent =
9038 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9039 .displayId(ADISPLAY_ID_DEFAULT)
9040 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07009041 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(150).y(150))
9042 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(10).y(10))
9043 .pointer(PointerBuilder(/*id=*/2, ToolType::FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009044 .build();
9045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9046 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
9047 InputEventInjectionSync::WAIT_FOR_RESULT))
9048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9049 spy->consumeMotionPointerDown(1);
9050 window->consumeMotionPointerDown(2);
9051
9052 // Spy window pilfers the pointers.
9053 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9054 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9055 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9056
9057 spy->assertNoEvents();
9058 window->assertNoEvents();
9059}
9060
9061/**
9062 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
9063 * other windows should be canceled. If this results in the cancellation of all pointers for some
9064 * window, then that window should receive ACTION_CANCEL.
9065 */
9066TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
9067 auto spy = createSpy();
9068 spy->setFrame(Rect(0, 0, 100, 100));
9069 auto window = createForeground();
9070 window->setFrame(Rect(0, 0, 200, 200));
9071
9072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9073
9074 // First finger down on both spy and window
9075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9077 {10, 10}))
9078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9079 window->consumeMotionDown();
9080 spy->consumeMotionDown();
9081
9082 // Second finger down on the spy and window
9083 const MotionEvent secondFingerDownEvent =
9084 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9085 .displayId(ADISPLAY_ID_DEFAULT)
9086 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07009087 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(10).y(10))
9088 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009089 .build();
9090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9091 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9092 InputEventInjectionSync::WAIT_FOR_RESULT))
9093 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9094 spy->consumeMotionPointerDown(1);
9095 window->consumeMotionPointerDown(1);
9096
9097 // Spy window pilfers the pointers.
9098 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9099 window->consumeMotionCancel();
9100
9101 spy->assertNoEvents();
9102 window->assertNoEvents();
9103}
9104
9105/**
9106 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
9107 * be sent to other windows
9108 */
9109TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
9110 auto spy = createSpy();
9111 spy->setFrame(Rect(0, 0, 100, 100));
9112 auto window = createForeground();
9113 window->setFrame(Rect(0, 0, 200, 200));
9114
9115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9116
9117 // First finger down on both window and spy
9118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9119 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9120 {10, 10}))
9121 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9122 window->consumeMotionDown();
9123 spy->consumeMotionDown();
9124
9125 // Spy window pilfers the pointers.
9126 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9127 window->consumeMotionCancel();
9128
9129 // Second finger down on the window only
9130 const MotionEvent secondFingerDownEvent =
9131 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9132 .displayId(ADISPLAY_ID_DEFAULT)
9133 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07009134 .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER).x(10).y(10))
9135 .pointer(PointerBuilder(/*id=*/1, ToolType::FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009136 .build();
9137 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9138 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9139 InputEventInjectionSync::WAIT_FOR_RESULT))
9140 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9141 window->consumeMotionDown();
9142 window->assertNoEvents();
9143
9144 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
9145 spy->consumeMotionMove();
9146 spy->assertNoEvents();
9147}
9148
Prabir Pradhand65552b2021-10-07 11:23:50 -07009149class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
9150public:
9151 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
9152 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9153 std::make_shared<FakeApplicationHandle>();
9154 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009155 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
9156 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009157 overlay->setFocusable(false);
9158 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08009159 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009160 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009161 overlay->setTrustedOverlay(true);
9162
9163 std::shared_ptr<FakeApplicationHandle> application =
9164 std::make_shared<FakeApplicationHandle>();
9165 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009166 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9167 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009168 window->setFocusable(true);
9169 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009170
9171 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9173 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009174 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009175 return {std::move(overlay), std::move(window)};
9176 }
9177
9178 void sendFingerEvent(int32_t action) {
9179 NotifyMotionArgs motionArgs =
9180 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9181 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9182 mDispatcher->notifyMotion(&motionArgs);
9183 }
9184
9185 void sendStylusEvent(int32_t action) {
9186 NotifyMotionArgs motionArgs =
9187 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9188 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07009189 motionArgs.pointerProperties[0].toolType = ToolType::STYLUS;
Prabir Pradhand65552b2021-10-07 11:23:50 -07009190 mDispatcher->notifyMotion(&motionArgs);
9191 }
9192};
9193
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009194using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9195
9196TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9197 ScopedSilentDeath _silentDeath;
9198
Prabir Pradhand65552b2021-10-07 11:23:50 -07009199 auto [overlay, window] = setupStylusOverlayScenario();
9200 overlay->setTrustedOverlay(false);
9201 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9202 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9203 ".* not a trusted overlay");
9204}
9205
9206TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9207 auto [overlay, window] = setupStylusOverlayScenario();
9208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9209
9210 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9211 overlay->consumeMotionDown();
9212 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9213 overlay->consumeMotionUp();
9214
9215 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9216 window->consumeMotionDown();
9217 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9218 window->consumeMotionUp();
9219
9220 overlay->assertNoEvents();
9221 window->assertNoEvents();
9222}
9223
9224TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9225 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009226 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9228
9229 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9230 overlay->consumeMotionDown();
9231 window->consumeMotionDown();
9232 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9233 overlay->consumeMotionUp();
9234 window->consumeMotionUp();
9235
9236 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9237 window->consumeMotionDown();
9238 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9239 window->consumeMotionUp();
9240
9241 overlay->assertNoEvents();
9242 window->assertNoEvents();
9243}
9244
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009245/**
9246 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9247 * The scenario is as follows:
9248 * - The stylus interceptor overlay is configured as a spy window.
9249 * - The stylus interceptor spy receives the start of a new stylus gesture.
9250 * - It pilfers pointers and then configures itself to no longer be a spy.
9251 * - The stylus interceptor continues to receive the rest of the gesture.
9252 */
9253TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9254 auto [overlay, window] = setupStylusOverlayScenario();
9255 overlay->setSpy(true);
9256 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9257
9258 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9259 overlay->consumeMotionDown();
9260 window->consumeMotionDown();
9261
9262 // The interceptor pilfers the pointers.
9263 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9264 window->consumeMotionCancel();
9265
9266 // The interceptor configures itself so that it is no longer a spy.
9267 overlay->setSpy(false);
9268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9269
9270 // It continues to receive the rest of the stylus gesture.
9271 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9272 overlay->consumeMotionMove();
9273 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9274 overlay->consumeMotionUp();
9275
9276 window->assertNoEvents();
9277}
9278
Prabir Pradhan5735a322022-04-11 17:23:34 +00009279struct User {
9280 int32_t mPid;
9281 int32_t mUid;
9282 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9283 std::unique_ptr<InputDispatcher>& mDispatcher;
9284
9285 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9286 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9287
9288 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9289 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9290 ADISPLAY_ID_DEFAULT, {100, 200},
9291 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9292 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9293 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9294 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9295 }
9296
9297 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009298 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009299 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009300 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009301 mPolicyFlags);
9302 }
9303
9304 sp<FakeWindowHandle> createWindow() const {
9305 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9306 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009307 sp<FakeWindowHandle> window =
9308 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9309 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009310 window->setOwnerInfo(mPid, mUid);
9311 return window;
9312 }
9313};
9314
9315using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9316
9317TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9318 auto owner = User(mDispatcher, 10, 11);
9319 auto window = owner.createWindow();
9320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9321
9322 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9323 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9324 window->consumeMotionDown();
9325
9326 setFocusedWindow(window);
9327 window->consumeFocusEvent(true);
9328
9329 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9330 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9331 window->consumeKeyDown(ADISPLAY_ID_NONE);
9332}
9333
9334TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9335 auto owner = User(mDispatcher, 10, 11);
9336 auto window = owner.createWindow();
9337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9338
9339 auto rando = User(mDispatcher, 20, 21);
9340 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9341 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9342
9343 setFocusedWindow(window);
9344 window->consumeFocusEvent(true);
9345
9346 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9347 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9348 window->assertNoEvents();
9349}
9350
9351TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9352 auto owner = User(mDispatcher, 10, 11);
9353 auto window = owner.createWindow();
9354 auto spy = owner.createWindow();
9355 spy->setSpy(true);
9356 spy->setTrustedOverlay(true);
9357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9358
9359 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9360 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9361 spy->consumeMotionDown();
9362 window->consumeMotionDown();
9363}
9364
9365TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9366 auto owner = User(mDispatcher, 10, 11);
9367 auto window = owner.createWindow();
9368
9369 auto rando = User(mDispatcher, 20, 21);
9370 auto randosSpy = rando.createWindow();
9371 randosSpy->setSpy(true);
9372 randosSpy->setTrustedOverlay(true);
9373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9374
9375 // The event is targeted at owner's window, so injection should succeed, but the spy should
9376 // not receive the event.
9377 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9378 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9379 randosSpy->assertNoEvents();
9380 window->consumeMotionDown();
9381}
9382
9383TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9384 auto owner = User(mDispatcher, 10, 11);
9385 auto window = owner.createWindow();
9386
9387 auto rando = User(mDispatcher, 20, 21);
9388 auto randosSpy = rando.createWindow();
9389 randosSpy->setSpy(true);
9390 randosSpy->setTrustedOverlay(true);
9391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9392
9393 // A user that has injection permission can inject into any window.
9394 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9395 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9396 ADISPLAY_ID_DEFAULT));
9397 randosSpy->consumeMotionDown();
9398 window->consumeMotionDown();
9399
9400 setFocusedWindow(randosSpy);
9401 randosSpy->consumeFocusEvent(true);
9402
9403 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9404 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9405 window->assertNoEvents();
9406}
9407
9408TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9409 auto owner = User(mDispatcher, 10, 11);
9410 auto window = owner.createWindow();
9411
9412 auto rando = User(mDispatcher, 20, 21);
9413 auto randosWindow = rando.createWindow();
9414 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9415 randosWindow->setWatchOutsideTouch(true);
9416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9417
9418 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9419 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9420 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9421 window->consumeMotionDown();
9422 randosWindow->consumeMotionOutside();
9423}
9424
Garfield Tane84e6f92019-08-29 17:28:41 -07009425} // namespace android::inputdispatcher