blob: 314233ec35189d2268b8a09603c5dc59756b21e4 [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);
233 EXPECT_EQ(motionEvent.getX(0), point.x);
234 EXPECT_EQ(motionEvent.getY(0), point.y);
235 EXPECT_EQ(motionEvent.getRawX(0), point.x);
236 EXPECT_EQ(motionEvent.getRawY(0), point.y);
237 });
Jackal Guof9696682018-10-05 12:23:23 +0800238 }
239
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700240 void assertFilterInputEventWasNotCalled() {
241 std::scoped_lock lock(mLock);
242 ASSERT_EQ(nullptr, mFilteredEvent);
243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800245 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700246 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800247 ASSERT_TRUE(mConfigurationChangedTime)
248 << "Timed out waiting for configuration changed call";
249 ASSERT_EQ(*mConfigurationChangedTime, when);
250 mConfigurationChangedTime = std::nullopt;
251 }
252
253 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700254 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800255 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800256 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800257 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
258 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
259 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
260 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
261 mLastNotifySwitch = std::nullopt;
262 }
263
chaviwfd6d3512019-03-25 13:23:49 -0700264 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700265 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800266 ASSERT_EQ(touchedToken, mOnPointerDownToken);
267 mOnPointerDownToken.clear();
268 }
269
270 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700271 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800272 ASSERT_TRUE(mOnPointerDownToken == nullptr)
273 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700274 }
275
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700276 // This function must be called soon after the expected ANR timer starts,
277 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500278 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700279 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500280 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800281 std::unique_lock lock(mLock);
282 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500283 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800284 ASSERT_NO_FATAL_FAILURE(
285 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500286 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700287 }
288
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000289 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800290 const sp<WindowInfoHandle>& window) {
291 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
292 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
293 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500294 }
295
Prabir Pradhanedd96402022-02-15 01:46:16 -0800296 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
297 const sp<IBinder>& expectedToken,
298 int32_t expectedPid) {
299 std::unique_lock lock(mLock);
300 android::base::ScopedLockAssertion assumeLocked(mLock);
301 AnrResult result;
302 ASSERT_NO_FATAL_FAILURE(result =
303 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
304 const auto& [token, pid] = result;
305 ASSERT_EQ(expectedToken, token);
306 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500307 }
308
Prabir Pradhanedd96402022-02-15 01:46:16 -0800309 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000310 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500311 std::unique_lock lock(mLock);
312 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800313 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
314 const auto& [token, _] = result;
315 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000316 }
317
Prabir Pradhanedd96402022-02-15 01:46:16 -0800318 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
319 int32_t expectedPid) {
320 std::unique_lock lock(mLock);
321 android::base::ScopedLockAssertion assumeLocked(mLock);
322 AnrResult result;
323 ASSERT_NO_FATAL_FAILURE(
324 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
325 const auto& [token, pid] = result;
326 ASSERT_EQ(expectedToken, token);
327 ASSERT_EQ(expectedPid, pid);
328 }
329
330 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000331 sp<IBinder> getResponsiveWindowToken() {
332 std::unique_lock lock(mLock);
333 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800334 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
335 const auto& [token, _] = result;
336 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700337 }
338
339 void assertNotifyAnrWasNotCalled() {
340 std::scoped_lock lock(mLock);
341 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800342 ASSERT_TRUE(mAnrWindows.empty());
343 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500344 << "ANR was not called, but please also consume the 'connection is responsive' "
345 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700346 }
347
Garfield Tan1c7bc862020-01-28 13:24:04 -0800348 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
349 mConfig.keyRepeatTimeout = timeout;
350 mConfig.keyRepeatDelay = delay;
351 }
352
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000353 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800354 std::unique_lock lock(mLock);
355 base::ScopedLockAssertion assumeLocked(mLock);
356
357 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
358 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000359 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800360 enabled;
361 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000362 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
363 << ") to be called.";
364 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800365 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000366 auto request = *mPointerCaptureRequest;
367 mPointerCaptureRequest.reset();
368 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800369 }
370
371 void assertSetPointerCaptureNotCalled() {
372 std::unique_lock lock(mLock);
373 base::ScopedLockAssertion assumeLocked(mLock);
374
375 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000376 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800377 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000378 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800379 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000380 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800381 }
382
arthurhungf452d0b2021-01-06 00:19:52 +0800383 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
384 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800385 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800386 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800387 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800388 }
389
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800390 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
391 std::unique_lock lock(mLock);
392 base::ScopedLockAssertion assumeLocked(mLock);
393 std::optional<sp<IBinder>> receivedToken =
394 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
395 mNotifyInputChannelBroken);
396 ASSERT_TRUE(receivedToken.has_value());
397 ASSERT_EQ(token, *receivedToken);
398 }
399
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800400 /**
401 * Set policy timeout. A value of zero means next key will not be intercepted.
402 */
403 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
404 mInterceptKeyTimeout = timeout;
405 }
406
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700408 std::mutex mLock;
409 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
410 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
411 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
412 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800413
Prabir Pradhan99987712020-11-10 18:43:05 -0800414 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000415
416 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800417
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700418 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700419 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800420 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
421 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700422 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800423 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
424 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700425
arthurhungf452d0b2021-01-06 00:19:52 +0800426 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800427 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800428
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800429 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
430
Prabir Pradhanedd96402022-02-15 01:46:16 -0800431 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
432 // for a specific container to become non-empty. When the container is non-empty, return the
433 // first entry from the container and erase it.
434 template <class T>
435 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
436 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
437 // If there is an ANR, Dispatcher won't be idle because there are still events
438 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
439 // before checking if ANR was called.
440 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
441 // to provide it some time to act. 100ms seems reasonable.
442 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
443 const std::chrono::time_point start = std::chrono::steady_clock::now();
444 std::optional<T> token =
445 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
446 if (!token.has_value()) {
447 ADD_FAILURE() << "Did not receive the ANR callback";
448 return {};
449 }
450
451 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
452 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
453 // the dispatcher started counting before this function was called
454 if (std::chrono::abs(timeout - waited) > 100ms) {
455 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
456 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
457 << "ms, but waited "
458 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
459 << "ms instead";
460 }
461 return *token;
462 }
463
464 template <class T>
465 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
466 std::queue<T>& storage,
467 std::unique_lock<std::mutex>& lock,
468 std::condition_variable& condition)
469 REQUIRES(mLock) {
470 condition.wait_for(lock, timeout,
471 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
472 if (storage.empty()) {
473 ADD_FAILURE() << "Did not receive the expected callback";
474 return std::nullopt;
475 }
476 T item = storage.front();
477 storage.pop();
478 return std::make_optional(item);
479 }
480
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600481 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700482 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800483 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484 }
485
Prabir Pradhanedd96402022-02-15 01:46:16 -0800486 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
487 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700488 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800489 ASSERT_TRUE(pid.has_value());
490 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700491 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500492 }
493
Prabir Pradhanedd96402022-02-15 01:46:16 -0800494 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
495 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500496 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800497 ASSERT_TRUE(pid.has_value());
498 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500499 mNotifyAnr.notify_all();
500 }
501
502 void notifyNoFocusedWindowAnr(
503 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
504 std::scoped_lock lock(mLock);
505 mAnrApplications.push(applicationHandle);
506 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 }
508
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800509 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
510 std::scoped_lock lock(mLock);
511 mBrokenInputChannels.push(connectionToken);
512 mNotifyInputChannelBroken.notify_all();
513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600515 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700516
Chris Yef59a2f42020-10-16 12:55:26 -0700517 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
518 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
519 const std::vector<float>& values) override {}
520
521 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
522 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000523
Chris Yefb552902021-02-03 17:18:37 -0800524 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
525
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600526 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 *outConfig = mConfig;
528 }
529
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600530 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700531 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800532 switch (inputEvent->getType()) {
533 case AINPUT_EVENT_TYPE_KEY: {
534 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800535 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800536 break;
537 }
538
539 case AINPUT_EVENT_TYPE_MOTION: {
540 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800541 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800542 break;
543 }
544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 return true;
546 }
547
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800548 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
549 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
550 // Clear intercept state when we handled the event.
551 mInterceptKeyTimeout = 0ms;
552 }
553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600555 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600557 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800558 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
559 // Clear intercept state so we could dispatch the event in next wake.
560 mInterceptKeyTimeout = 0ms;
561 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600564 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 return false;
566 }
567
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600568 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
569 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700570 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800571 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
572 * essentially a passthrough for notifySwitch.
573 */
Harry Cutts33476232023-01-30 19:57:29 +0000574 mLastNotifySwitch = NotifySwitchArgs(/*id=*/1, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 }
576
Sean Stoutb4e0a592021-02-23 07:34:53 -0800577 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600579 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700580 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700581 mOnPointerDownToken = newToken;
582 }
583
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000584 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800585 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000586 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800587 mPointerCaptureChangedCondition.notify_all();
588 }
589
arthurhungf452d0b2021-01-06 00:19:52 +0800590 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
591 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800592 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800593 mDropTargetWindowToken = token;
594 }
595
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700596 void assertFilterInputEventWasCalledInternal(
597 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700598 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800599 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700600 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800601 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603};
604
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605// --- InputDispatcherTest ---
606
607class InputDispatcherTest : public testing::Test {
608protected:
609 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700610 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000612 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700613 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800614 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800615 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000616 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700617 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 }
619
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000620 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700621 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700623 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700625
626 /**
627 * Used for debugging when writing the test
628 */
629 void dumpDispatcherState() {
630 std::string dump;
631 mDispatcher->dump(dump);
632 std::stringstream ss(dump);
633 std::string to;
634
635 while (std::getline(ss, to, '\n')) {
636 ALOGE("%s", to.c_str());
637 }
638 }
Vishnu Nair958da932020-08-21 17:12:37 -0700639
chaviw3277faf2021-05-19 16:45:23 -0500640 void setFocusedWindow(const sp<WindowInfoHandle>& window,
641 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700642 FocusRequest request;
643 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000644 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700645 if (focusedWindow) {
646 request.focusedToken = focusedWindow->getToken();
647 }
648 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
649 request.displayId = window->getInfo()->displayId;
650 mDispatcher->setFocusedWindow(request);
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652};
653
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
655 KeyEvent event;
656
657 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800658 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
659 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600660 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
661 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800662 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000663 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000664 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 << "Should reject key events with undefined action.";
666
667 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800668 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
669 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600670 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000672 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000673 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 << "Should reject key events with ACTION_MULTIPLE.";
675}
676
677TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
678 MotionEvent event;
679 PointerProperties pointerProperties[MAX_POINTERS + 1];
680 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800681 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 pointerProperties[i].clear();
683 pointerProperties[i].id = i;
684 pointerCoords[i].clear();
685 }
686
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800687 // Some constants commonly used below
688 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
689 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
690 constexpr int32_t metaState = AMETA_NONE;
691 constexpr MotionClassification classification = MotionClassification::NONE;
692
chaviw9eaa22c2020-07-01 16:21:27 -0700693 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800695 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700696 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
697 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700698 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
699 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700700 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800701 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000702 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000703 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 << "Should reject motion events with undefined action.";
705
706 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800707 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800708 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
709 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
710 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
711 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500712 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800713 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000714 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000715 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 << "Should reject motion events with pointer down index too large.";
717
Garfield Tanfbe732e2020-01-24 11:26:14 -0800718 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700719 AMOTION_EVENT_ACTION_POINTER_DOWN |
720 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700721 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
722 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700723 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500724 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800725 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000726 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000727 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 << "Should reject motion events with pointer down index too small.";
729
730 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800731 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800732 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
733 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
734 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
735 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500736 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000738 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000739 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 << "Should reject motion events with pointer up index too large.";
741
Garfield Tanfbe732e2020-01-24 11:26:14 -0800742 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700743 AMOTION_EVENT_ACTION_POINTER_UP |
744 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700745 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
746 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700747 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500748 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800749 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000750 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000751 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 << "Should reject motion events with pointer up index too small.";
753
754 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800755 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
756 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700757 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700758 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
759 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700760 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800761 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000762 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000763 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 << "Should reject motion events with 0 pointers.";
765
Garfield Tanfbe732e2020-01-24 11:26:14 -0800766 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
767 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700768 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700769 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
770 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800772 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000773 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000774 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 << "Should reject motion events with more than MAX_POINTERS pointers.";
776
777 // Rejects motion events with invalid pointer ids.
778 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800779 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
780 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700781 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700782 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
783 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700784 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800785 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000786 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000787 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 << "Should reject motion events with pointer ids less than 0.";
789
790 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800791 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
792 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700793 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700794 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
795 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700796 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800797 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000798 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000799 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
801
802 // Rejects motion events with duplicate pointer ids.
803 pointerProperties[0].id = 1;
804 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800805 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
806 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700807 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700808 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
809 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700810 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800811 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000812 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000813 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 << "Should reject motion events with duplicate pointer ids.";
815}
816
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800817/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
818
819TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
820 constexpr nsecs_t eventTime = 20;
Harry Cutts33476232023-01-30 19:57:29 +0000821 NotifyConfigurationChangedArgs args(/*id=*/10, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800822 mDispatcher->notifyConfigurationChanged(&args);
823 ASSERT_TRUE(mDispatcher->waitForIdle());
824
825 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
826}
827
828TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Harry Cutts33476232023-01-30 19:57:29 +0000829 NotifySwitchArgs args(/*id=*/10, /*eventTime=*/20, /*policyFlags=*/0, /*switchValues=*/1,
830 /*switchMask=*/2);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800831 mDispatcher->notifySwitch(&args);
832
833 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
834 args.policyFlags |= POLICY_FLAG_TRUSTED;
835 mFakePolicy->assertNotifySwitchWasCalled(args);
836}
837
Arthur Hungb92218b2018-08-14 12:00:21 +0800838// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700839static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700840// Default input dispatching timeout if there is no focused application or paused window
841// from which to determine an appropriate dispatching timeout.
842static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
843 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
844 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800845
846class FakeApplicationHandle : public InputApplicationHandle {
847public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700848 FakeApplicationHandle() {
849 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700850 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500851 mInfo.dispatchingTimeoutMillis =
852 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700853 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800854 virtual ~FakeApplicationHandle() {}
855
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000856 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700857
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500858 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
859 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700860 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800861};
862
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800863class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800864public:
Garfield Tan15601662020-09-22 15:32:38 -0700865 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800866 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700867 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800868 }
869
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800870 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700871 InputEvent* event;
872 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
873 if (!consumeSeq) {
874 return nullptr;
875 }
876 finishEvent(*consumeSeq);
877 return event;
878 }
879
880 /**
881 * Receive an event without acknowledging it.
882 * Return the sequence number that could later be used to send finished signal.
883 */
884 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800885 uint32_t consumeSeq;
886 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800887
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800888 std::chrono::time_point start = std::chrono::steady_clock::now();
889 status_t status = WOULD_BLOCK;
890 while (status == WOULD_BLOCK) {
Harry Cutts33476232023-01-30 19:57:29 +0000891 status = mConsumer->consume(&mEventFactory, /*consumeBatches=*/true, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800892 &event);
893 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
894 if (elapsed > 100ms) {
895 break;
896 }
897 }
898
899 if (status == WOULD_BLOCK) {
900 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700901 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800902 }
903
904 if (status != OK) {
905 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700906 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800907 }
908 if (event == nullptr) {
909 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700910 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800911 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700912 if (outEvent != nullptr) {
913 *outEvent = event;
914 }
915 return consumeSeq;
916 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800917
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700918 /**
919 * To be used together with "receiveEvent" to complete the consumption of an event.
920 */
921 void finishEvent(uint32_t consumeSeq) {
922 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
923 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800924 }
925
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000926 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
927 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
928 ASSERT_EQ(OK, status);
929 }
930
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000931 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
932 std::optional<int32_t> expectedDisplayId,
933 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800934 InputEvent* event = consume();
935
936 ASSERT_NE(nullptr, event) << mName.c_str()
937 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800938 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800940 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800941
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000942 if (expectedDisplayId.has_value()) {
943 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
944 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800945
Tiger Huang8664f8c2018-10-11 19:14:35 +0800946 switch (expectedEventType) {
947 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800948 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
949 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000950 if (expectedFlags.has_value()) {
951 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
952 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800953 break;
954 }
955 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800956 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000957 assertMotionAction(expectedAction, motionEvent.getAction());
958
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000959 if (expectedFlags.has_value()) {
960 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
961 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800962 break;
963 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100964 case AINPUT_EVENT_TYPE_FOCUS: {
965 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
966 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800967 case AINPUT_EVENT_TYPE_CAPTURE: {
968 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
969 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000970 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
971 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
972 }
arthurhungb89ccb02020-12-30 16:19:01 +0800973 case AINPUT_EVENT_TYPE_DRAG: {
974 FAIL() << "Use 'consumeDragEvent' for DRAG events";
975 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800976 default: {
977 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
978 }
979 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800980 }
981
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800982 MotionEvent* consumeMotion() {
983 InputEvent* event = consume();
984
985 if (event == nullptr) {
986 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
987 return nullptr;
988 }
989
990 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
991 ADD_FAILURE() << mName << " expected a MotionEvent, got "
992 << inputEventTypeToString(event->getType()) << " event";
993 return nullptr;
994 }
995 return static_cast<MotionEvent*>(event);
996 }
997
998 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
999 MotionEvent* motionEvent = consumeMotion();
1000 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
1001 ASSERT_THAT(*motionEvent, matcher);
1002 }
1003
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001004 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
1005 InputEvent* event = consume();
1006 ASSERT_NE(nullptr, event) << mName.c_str()
1007 << ": consumer should have returned non-NULL event.";
1008 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
1009 << "Got " << inputEventTypeToString(event->getType())
1010 << " event instead of FOCUS event";
1011
1012 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1013 << mName.c_str() << ": event displayId should always be NONE.";
1014
1015 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
1016 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001017 }
1018
Prabir Pradhan99987712020-11-10 18:43:05 -08001019 void consumeCaptureEvent(bool hasCapture) {
1020 const InputEvent* event = consume();
1021 ASSERT_NE(nullptr, event) << mName.c_str()
1022 << ": consumer should have returned non-NULL event.";
1023 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
1024 << "Got " << inputEventTypeToString(event->getType())
1025 << " event instead of CAPTURE event";
1026
1027 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1028 << mName.c_str() << ": event displayId should always be NONE.";
1029
1030 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1031 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1032 }
1033
arthurhungb89ccb02020-12-30 16:19:01 +08001034 void consumeDragEvent(bool isExiting, float x, float y) {
1035 const InputEvent* event = consume();
1036 ASSERT_NE(nullptr, event) << mName.c_str()
1037 << ": consumer should have returned non-NULL event.";
1038 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1039 << "Got " << inputEventTypeToString(event->getType())
1040 << " event instead of DRAG event";
1041
1042 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1043 << mName.c_str() << ": event displayId should always be NONE.";
1044
1045 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1046 EXPECT_EQ(isExiting, dragEvent.isExiting());
1047 EXPECT_EQ(x, dragEvent.getX());
1048 EXPECT_EQ(y, dragEvent.getY());
1049 }
1050
Antonio Kantekf16f2832021-09-28 04:39:20 +00001051 void consumeTouchModeEvent(bool inTouchMode) {
1052 const InputEvent* event = consume();
1053 ASSERT_NE(nullptr, event) << mName.c_str()
1054 << ": consumer should have returned non-NULL event.";
1055 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1056 << "Got " << inputEventTypeToString(event->getType())
1057 << " event instead of TOUCH_MODE event";
1058
1059 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1060 << mName.c_str() << ": event displayId should always be NONE.";
1061 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1062 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1063 }
1064
chaviwd1c23182019-12-20 18:44:56 -08001065 void assertNoEvents() {
1066 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 if (event == nullptr) {
1068 return;
1069 }
1070 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1071 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1072 ADD_FAILURE() << "Received key event "
1073 << KeyEvent::actionToString(keyEvent.getAction());
1074 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1075 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1076 ADD_FAILURE() << "Received motion event "
1077 << MotionEvent::actionToString(motionEvent.getAction());
1078 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1079 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1080 ADD_FAILURE() << "Received focus event, hasFocus = "
1081 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001082 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1083 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1084 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1085 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001086 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1087 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1088 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1089 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001090 }
1091 FAIL() << mName.c_str()
1092 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001093 }
1094
1095 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1096
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001097 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1098
chaviwd1c23182019-12-20 18:44:56 -08001099protected:
1100 std::unique_ptr<InputConsumer> mConsumer;
1101 PreallocatedInputEventFactory mEventFactory;
1102
1103 std::string mName;
1104};
1105
chaviw3277faf2021-05-19 16:45:23 -05001106class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001107public:
1108 static const int32_t WIDTH = 600;
1109 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001110
Chris Yea209fde2020-07-22 13:54:51 -07001111 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001112 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001113 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001114 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001115 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001116 base::Result<std::unique_ptr<InputChannel>> channel =
1117 dispatcher->createInputChannel(name);
1118 token = (*channel)->getConnectionToken();
1119 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001120 }
1121
1122 inputApplicationHandle->updateInfo();
1123 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1124
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001125 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001126 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001127 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001128 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001129 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001130 mInfo.frameLeft = 0;
1131 mInfo.frameTop = 0;
1132 mInfo.frameRight = WIDTH;
1133 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001134 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001135 mInfo.globalScaleFactor = 1.0;
1136 mInfo.touchableRegion.clear();
1137 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001138 mInfo.ownerPid = WINDOW_PID;
1139 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001140 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001141 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001142 }
1143
Arthur Hungabbb9d82021-09-01 14:52:30 +00001144 sp<FakeWindowHandle> clone(
1145 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001146 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001147 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001148 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1149 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001150 return handle;
1151 }
1152
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001153 void setTouchable(bool touchable) {
1154 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1155 }
chaviwd1c23182019-12-20 18:44:56 -08001156
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001157 void setFocusable(bool focusable) {
1158 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1159 }
1160
1161 void setVisible(bool visible) {
1162 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1163 }
Vishnu Nair958da932020-08-21 17:12:37 -07001164
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001165 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001166 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001167 }
1168
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001169 void setPaused(bool paused) {
1170 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1171 }
1172
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001173 void setPreventSplitting(bool preventSplitting) {
1174 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001175 }
1176
1177 void setSlippery(bool slippery) {
1178 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1179 }
1180
1181 void setWatchOutsideTouch(bool watchOutside) {
1182 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1183 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001184
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001185 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1186
1187 void setInterceptsStylus(bool interceptsStylus) {
1188 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1189 }
1190
1191 void setDropInput(bool dropInput) {
1192 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1193 }
1194
1195 void setDropInputIfObscured(bool dropInputIfObscured) {
1196 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1197 }
1198
1199 void setNoInputChannel(bool noInputChannel) {
1200 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1201 }
1202
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001203 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1204
chaviw3277faf2021-05-19 16:45:23 -05001205 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001206
Bernardo Rufino7393d172021-02-26 13:56:11 +00001207 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1208
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001209 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001210 mInfo.frameLeft = frame.left;
1211 mInfo.frameTop = frame.top;
1212 mInfo.frameRight = frame.right;
1213 mInfo.frameBottom = frame.bottom;
1214 mInfo.touchableRegion.clear();
1215 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001216
1217 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1218 ui::Transform translate;
1219 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1220 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001221 }
1222
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001223 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1224
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001225 void setIsWallpaper(bool isWallpaper) {
1226 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1227 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001228
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001229 void setDupTouchToWallpaper(bool hasWallpaper) {
1230 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1231 }
chaviwd1c23182019-12-20 18:44:56 -08001232
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001233 void setTrustedOverlay(bool trustedOverlay) {
1234 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1235 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001236
chaviw9eaa22c2020-07-01 16:21:27 -07001237 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1238 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1239 }
1240
1241 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001242
yunho.shinf4a80b82020-11-16 21:13:57 +09001243 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1244
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001245 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1246 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1247 expectedFlags);
1248 }
1249
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001250 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1251 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1252 }
1253
Svet Ganov5d3bc372020-01-26 23:11:07 -08001254 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001255 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001256 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1257 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001258 }
1259
1260 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001261 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001262 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1263 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001264 }
1265
1266 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001267 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001268 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1269 }
1270
1271 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1272 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001273 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1274 expectedFlags);
1275 }
1276
Svet Ganov5d3bc372020-01-26 23:11:07 -08001277 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001278 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1279 int32_t expectedFlags = 0) {
1280 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1281 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001282 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1283 }
1284
1285 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001286 int32_t expectedFlags = 0) {
1287 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1288 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001289 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1290 }
1291
1292 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001293 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001294 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1295 expectedFlags);
1296 }
1297
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001298 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1299 int32_t expectedFlags = 0) {
1300 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1301 expectedFlags);
1302 }
1303
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001304 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1305 int32_t expectedFlags = 0) {
1306 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001307 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001308 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1309 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1310 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1311 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1312 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1313 }
1314
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001315 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1316 ASSERT_NE(mInputReceiver, nullptr)
1317 << "Cannot consume events from a window with no receiver";
1318 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1319 }
1320
Prabir Pradhan99987712020-11-10 18:43:05 -08001321 void consumeCaptureEvent(bool hasCapture) {
1322 ASSERT_NE(mInputReceiver, nullptr)
1323 << "Cannot consume events from a window with no receiver";
1324 mInputReceiver->consumeCaptureEvent(hasCapture);
1325 }
1326
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001327 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1328 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001329 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001330 ASSERT_THAT(*motionEvent, matcher);
1331 }
1332
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001333 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1334 std::optional<int32_t> expectedDisplayId,
1335 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001336 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1337 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1338 expectedFlags);
1339 }
1340
arthurhungb89ccb02020-12-30 16:19:01 +08001341 void consumeDragEvent(bool isExiting, float x, float y) {
1342 mInputReceiver->consumeDragEvent(isExiting, x, y);
1343 }
1344
Antonio Kantekf16f2832021-09-28 04:39:20 +00001345 void consumeTouchModeEvent(bool inTouchMode) {
1346 ASSERT_NE(mInputReceiver, nullptr)
1347 << "Cannot consume events from a window with no receiver";
1348 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1349 }
1350
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001351 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001352 if (mInputReceiver == nullptr) {
1353 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1354 return std::nullopt;
1355 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001356 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001357 }
1358
1359 void finishEvent(uint32_t sequenceNum) {
1360 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1361 mInputReceiver->finishEvent(sequenceNum);
1362 }
1363
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001364 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1365 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1366 mInputReceiver->sendTimeline(inputEventId, timeline);
1367 }
1368
chaviwaf87b3e2019-10-01 16:59:28 -07001369 InputEvent* consume() {
1370 if (mInputReceiver == nullptr) {
1371 return nullptr;
1372 }
1373 return mInputReceiver->consume();
1374 }
1375
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001376 MotionEvent* consumeMotion() {
1377 InputEvent* event = consume();
1378 if (event == nullptr) {
1379 ADD_FAILURE() << "Consume failed : no event";
1380 return nullptr;
1381 }
1382 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1383 ADD_FAILURE() << "Instead of motion event, got "
1384 << inputEventTypeToString(event->getType());
1385 return nullptr;
1386 }
1387 return static_cast<MotionEvent*>(event);
1388 }
1389
Arthur Hungb92218b2018-08-14 12:00:21 +08001390 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001391 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001392 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001393 return; // Can't receive events if the window does not have input channel
1394 }
1395 ASSERT_NE(nullptr, mInputReceiver)
1396 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001397 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001398 }
1399
chaviwaf87b3e2019-10-01 16:59:28 -07001400 sp<IBinder> getToken() { return mInfo.token; }
1401
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001402 const std::string& getName() { return mName; }
1403
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001404 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1405 mInfo.ownerPid = ownerPid;
1406 mInfo.ownerUid = ownerUid;
1407 }
1408
Prabir Pradhanedd96402022-02-15 01:46:16 -08001409 int32_t getPid() const { return mInfo.ownerPid; }
1410
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001411 void destroyReceiver() { mInputReceiver = nullptr; }
1412
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001413 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1414
chaviwd1c23182019-12-20 18:44:56 -08001415private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001416 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001417 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001418 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001419};
1420
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001421std::atomic<int32_t> FakeWindowHandle::sId{1};
1422
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001423static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001424 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001425 int32_t displayId = ADISPLAY_ID_NONE,
1426 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001427 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001428 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1429 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001430 KeyEvent event;
1431 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1432
1433 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001434 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Harry Cutts33476232023-01-30 19:57:29 +00001435 INVALID_HMAC, action, /*flags=*/0, AKEYCODE_A, KEY_A, AMETA_NONE, repeatCount,
1436 currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001437
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001438 if (!allowKeyRepeat) {
1439 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1440 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001441 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001442 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001443}
1444
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001445static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001446 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001447 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001448}
1449
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001450// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1451// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1452// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453static InputEventInjectionResult injectKeyDownNoRepeat(
1454 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001455 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001456 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
Harry Cutts33476232023-01-30 19:57:29 +00001457 /*allowKeyRepeat=*/false);
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001458}
1459
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001460static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001462 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /*repeatCount=*/0, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463}
1464
Garfield Tandf26e862020-07-01 20:18:19 -07001465class PointerBuilder {
1466public:
1467 PointerBuilder(int32_t id, int32_t toolType) {
1468 mProperties.clear();
1469 mProperties.id = id;
1470 mProperties.toolType = toolType;
1471 mCoords.clear();
1472 }
1473
1474 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1475
1476 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1477
1478 PointerBuilder& axis(int32_t axis, float value) {
1479 mCoords.setAxisValue(axis, value);
1480 return *this;
1481 }
1482
1483 PointerProperties buildProperties() const { return mProperties; }
1484
1485 PointerCoords buildCoords() const { return mCoords; }
1486
1487private:
1488 PointerProperties mProperties;
1489 PointerCoords mCoords;
1490};
1491
1492class MotionEventBuilder {
1493public:
1494 MotionEventBuilder(int32_t action, int32_t source) {
1495 mAction = action;
1496 mSource = source;
1497 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001498 mDownTime = mEventTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001499 }
1500
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001501 MotionEventBuilder& deviceId(int32_t deviceId) {
1502 mDeviceId = deviceId;
1503 return *this;
1504 }
1505
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001506 MotionEventBuilder& downTime(nsecs_t downTime) {
1507 mDownTime = downTime;
1508 return *this;
1509 }
1510
Garfield Tandf26e862020-07-01 20:18:19 -07001511 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1512 mEventTime = eventTime;
1513 return *this;
1514 }
1515
1516 MotionEventBuilder& displayId(int32_t displayId) {
1517 mDisplayId = displayId;
1518 return *this;
1519 }
1520
1521 MotionEventBuilder& actionButton(int32_t actionButton) {
1522 mActionButton = actionButton;
1523 return *this;
1524 }
1525
arthurhung6d4bed92021-03-17 11:59:33 +08001526 MotionEventBuilder& buttonState(int32_t buttonState) {
1527 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001528 return *this;
1529 }
1530
1531 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1532 mRawXCursorPosition = rawXCursorPosition;
1533 return *this;
1534 }
1535
1536 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1537 mRawYCursorPosition = rawYCursorPosition;
1538 return *this;
1539 }
1540
1541 MotionEventBuilder& pointer(PointerBuilder pointer) {
1542 mPointers.push_back(pointer);
1543 return *this;
1544 }
1545
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001546 MotionEventBuilder& addFlag(uint32_t flags) {
1547 mFlags |= flags;
1548 return *this;
1549 }
1550
Garfield Tandf26e862020-07-01 20:18:19 -07001551 MotionEvent build() {
1552 std::vector<PointerProperties> pointerProperties;
1553 std::vector<PointerCoords> pointerCoords;
1554 for (const PointerBuilder& pointer : mPointers) {
1555 pointerProperties.push_back(pointer.buildProperties());
1556 pointerCoords.push_back(pointer.buildCoords());
1557 }
1558
1559 // Set mouse cursor position for the most common cases to avoid boilerplate.
1560 if (mSource == AINPUT_SOURCE_MOUSE &&
1561 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1562 mPointers.size() == 1) {
1563 mRawXCursorPosition = pointerCoords[0].getX();
1564 mRawYCursorPosition = pointerCoords[0].getY();
1565 }
1566
1567 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001568 ui::Transform identityTransform;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001569 event.initialize(InputEvent::nextId(), mDeviceId, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001570 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001571 mButtonState, MotionClassification::NONE, identityTransform,
1572 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001573 mRawYCursorPosition, identityTransform, mDownTime, mEventTime,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001574 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001575
1576 return event;
1577 }
1578
1579private:
1580 int32_t mAction;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001581 int32_t mDeviceId = DEVICE_ID;
Garfield Tandf26e862020-07-01 20:18:19 -07001582 int32_t mSource;
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001583 nsecs_t mDownTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001584 nsecs_t mEventTime;
1585 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1586 int32_t mActionButton{0};
1587 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001588 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001589 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1590 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1591
1592 std::vector<PointerBuilder> mPointers;
1593};
1594
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08001595class MotionArgsBuilder {
1596public:
1597 MotionArgsBuilder(int32_t action, int32_t source) {
1598 mAction = action;
1599 mSource = source;
1600 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1601 mDownTime = mEventTime;
1602 }
1603
1604 MotionArgsBuilder& deviceId(int32_t deviceId) {
1605 mDeviceId = deviceId;
1606 return *this;
1607 }
1608
1609 MotionArgsBuilder& downTime(nsecs_t downTime) {
1610 mDownTime = downTime;
1611 return *this;
1612 }
1613
1614 MotionArgsBuilder& eventTime(nsecs_t eventTime) {
1615 mEventTime = eventTime;
1616 return *this;
1617 }
1618
1619 MotionArgsBuilder& displayId(int32_t displayId) {
1620 mDisplayId = displayId;
1621 return *this;
1622 }
1623
1624 MotionArgsBuilder& policyFlags(int32_t policyFlags) {
1625 mPolicyFlags = policyFlags;
1626 return *this;
1627 }
1628
1629 MotionArgsBuilder& actionButton(int32_t actionButton) {
1630 mActionButton = actionButton;
1631 return *this;
1632 }
1633
1634 MotionArgsBuilder& buttonState(int32_t buttonState) {
1635 mButtonState = buttonState;
1636 return *this;
1637 }
1638
1639 MotionArgsBuilder& rawXCursorPosition(float rawXCursorPosition) {
1640 mRawXCursorPosition = rawXCursorPosition;
1641 return *this;
1642 }
1643
1644 MotionArgsBuilder& rawYCursorPosition(float rawYCursorPosition) {
1645 mRawYCursorPosition = rawYCursorPosition;
1646 return *this;
1647 }
1648
1649 MotionArgsBuilder& pointer(PointerBuilder pointer) {
1650 mPointers.push_back(pointer);
1651 return *this;
1652 }
1653
1654 MotionArgsBuilder& addFlag(uint32_t flags) {
1655 mFlags |= flags;
1656 return *this;
1657 }
1658
1659 NotifyMotionArgs build() {
1660 std::vector<PointerProperties> pointerProperties;
1661 std::vector<PointerCoords> pointerCoords;
1662 for (const PointerBuilder& pointer : mPointers) {
1663 pointerProperties.push_back(pointer.buildProperties());
1664 pointerCoords.push_back(pointer.buildCoords());
1665 }
1666
1667 // Set mouse cursor position for the most common cases to avoid boilerplate.
1668 if (mSource == AINPUT_SOURCE_MOUSE &&
1669 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1670 mPointers.size() == 1) {
1671 mRawXCursorPosition = pointerCoords[0].getX();
1672 mRawYCursorPosition = pointerCoords[0].getY();
1673 }
1674
1675 NotifyMotionArgs args(InputEvent::nextId(), mEventTime, /*readTime=*/mEventTime, mDeviceId,
1676 mSource, mDisplayId, mPolicyFlags, mAction, mActionButton, mFlags,
1677 AMETA_NONE, mButtonState, MotionClassification::NONE, /*edgeFlags=*/0,
1678 mPointers.size(), pointerProperties.data(), pointerCoords.data(),
1679 /*xPrecision=*/0, /*yPrecision=*/0, mRawXCursorPosition,
1680 mRawYCursorPosition, mDownTime, /*videoFrames=*/{});
1681
1682 return args;
1683 }
1684
1685private:
1686 int32_t mAction;
1687 int32_t mDeviceId = DEVICE_ID;
1688 int32_t mSource;
1689 nsecs_t mDownTime;
1690 nsecs_t mEventTime;
1691 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1692 int32_t mPolicyFlags = DEFAULT_POLICY_FLAGS;
1693 int32_t mActionButton{0};
1694 int32_t mButtonState{0};
1695 int32_t mFlags{0};
1696 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1697 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1698
1699 std::vector<PointerBuilder> mPointers;
1700};
1701
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001702static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001703 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001704 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001705 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1706 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1707 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1708 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001709}
1710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001711static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001712 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001713 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001714 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001715 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1716 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001718 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1719 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001720 MotionEvent event = MotionEventBuilder(action, source)
1721 .displayId(displayId)
1722 .eventTime(eventTime)
1723 .rawXCursorPosition(cursorPosition.x)
1724 .rawYCursorPosition(cursorPosition.y)
Harry Cutts33476232023-01-30 19:57:29 +00001725 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001726 .x(position.x)
1727 .y(position.y))
1728 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001729
1730 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001731 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1732 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001733}
1734
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001735static InputEventInjectionResult injectMotionDown(
1736 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1737 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001738 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001739}
1740
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001741static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001742 int32_t source, int32_t displayId,
1743 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001744 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001745}
1746
Jackal Guof9696682018-10-05 12:23:23 +08001747static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1748 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1749 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001750 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001751 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1752 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001753
1754 return args;
1755}
1756
chaviwd1c23182019-12-20 18:44:56 -08001757static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1758 const std::vector<PointF>& points) {
1759 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001760 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1761 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1762 }
1763
chaviwd1c23182019-12-20 18:44:56 -08001764 PointerProperties pointerProperties[pointerCount];
1765 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001766
chaviwd1c23182019-12-20 18:44:56 -08001767 for (size_t i = 0; i < pointerCount; i++) {
1768 pointerProperties[i].clear();
1769 pointerProperties[i].id = i;
1770 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001771
chaviwd1c23182019-12-20 18:44:56 -08001772 pointerCoords[i].clear();
1773 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1774 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1775 }
Jackal Guof9696682018-10-05 12:23:23 +08001776
1777 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1778 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001779 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001780 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1781 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001782 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1783 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001784 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1785 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001786
1787 return args;
1788}
1789
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001790static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1791 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1792}
1793
chaviwd1c23182019-12-20 18:44:56 -08001794static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1795 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1796}
1797
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001798static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1799 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001800 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001801}
1802
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001803/**
1804 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1805 * broken channel.
1806 */
1807TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1808 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1809 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001810 sp<FakeWindowHandle>::make(application, mDispatcher,
1811 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001812
1813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1814
1815 // Window closes its channel, but the window remains.
1816 window->destroyReceiver();
1817 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1818}
1819
Arthur Hungb92218b2018-08-14 12:00:21 +08001820TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001821 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001822 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1823 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001824
Arthur Hung72d8dc32020-03-28 00:48:39 +00001825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1827 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1828 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001829
1830 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001831 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001832}
1833
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001834TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1835 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001836 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1837 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001838
1839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1840 // Inject a MotionEvent to an unknown display.
1841 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1842 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1843 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1844
1845 // Window should receive motion event.
1846 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1847}
1848
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001849/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001850 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001851 * This test serves as a sanity check for the next test, where setInputWindows is
1852 * called twice.
1853 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001854TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001856 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1857 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001858 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001859
1860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1863 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001864 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001865
1866 // Window should receive motion event.
1867 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1868}
1869
1870/**
1871 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001872 */
1873TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001875 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1876 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001877 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001878
1879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001882 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1883 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001885
1886 // Window should receive motion event.
1887 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1888}
1889
Arthur Hungb92218b2018-08-14 12:00:21 +08001890// The foreground window should receive the first touch down event.
1891TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001892 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001893 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001894 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001895 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001896 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001897
Arthur Hung72d8dc32020-03-28 00:48:39 +00001898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1900 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1901 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001902
1903 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001904 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001905 windowSecond->assertNoEvents();
1906}
1907
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001908/**
1909 * Two windows: A top window, and a wallpaper behind the window.
1910 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1911 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001912 * 1. foregroundWindow <-- dup touch to wallpaper
1913 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001914 */
1915TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1917 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001918 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001919 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001920 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001921 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001922 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001923
1924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1926 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1927 {100, 200}))
1928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1929
1930 // Both foreground window and its wallpaper should receive the touch down
1931 foregroundWindow->consumeMotionDown();
1932 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1933
1934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1935 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1936 ADISPLAY_ID_DEFAULT, {110, 200}))
1937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1938
1939 foregroundWindow->consumeMotionMove();
1940 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1941
1942 // Now the foreground window goes away, but the wallpaper stays
1943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1944 foregroundWindow->consumeMotionCancel();
1945 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1946 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1947}
1948
1949/**
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08001950 * Two fingers down on the window, and lift off the first finger.
1951 * Next, cancel the gesture to the window by removing the window. Make sure that the CANCEL event
1952 * contains a single pointer.
1953 */
1954TEST_F(InputDispatcherTest, CancelAfterPointer0Up) {
1955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1956 sp<FakeWindowHandle> window =
1957 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1958
1959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1960 NotifyMotionArgs args;
1961 // First touch pointer down on right window
1962 mDispatcher->notifyMotion(&(
1963 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1964 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1965 .build()));
1966 // Second touch pointer down
1967 mDispatcher->notifyMotion(&(
1968 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1969
1970 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1971 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(110).y(100))
1972 .build()));
1973 // First touch pointer lifts. The second one remains down
1974 mDispatcher->notifyMotion(&(
1975 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1976
1977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1978 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(110).y(100))
1979 .build()));
1980 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
1981 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
1982 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
1983
1984 // Remove the window. The gesture should be canceled
1985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
1986 const std::map<int32_t, PointF> expectedPointers{{1, PointF{110, 100}}};
1987 window->consumeMotionEvent(
1988 AllOf(WithMotionAction(ACTION_CANCEL), WithPointers(expectedPointers)));
1989}
1990
1991/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001992 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1993 * with the following differences:
1994 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1995 * clean up the connection.
1996 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1997 * Ensure that there's no crash in the dispatcher.
1998 */
1999TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
2000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2001 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002002 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002003 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002004 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002005 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002006 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002007
2008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
2009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2010 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2011 {100, 200}))
2012 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2013
2014 // Both foreground window and its wallpaper should receive the touch down
2015 foregroundWindow->consumeMotionDown();
2016 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2017
2018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2019 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2020 ADISPLAY_ID_DEFAULT, {110, 200}))
2021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2022
2023 foregroundWindow->consumeMotionMove();
2024 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2025
2026 // Wallpaper closes its channel, but the window remains.
2027 wallpaperWindow->destroyReceiver();
2028 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
2029
2030 // Now the foreground window goes away, but the wallpaper stays, even though its channel
2031 // is no longer valid.
2032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
2033 foregroundWindow->consumeMotionCancel();
2034}
2035
Arthur Hungc539dbb2022-12-08 07:45:36 +00002036class ShouldSplitTouchFixture : public InputDispatcherTest,
2037 public ::testing::WithParamInterface<bool> {};
2038INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
2039 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08002040/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002041 * A single window that receives touch (on top), and a wallpaper window underneath it.
2042 * The top window gets a multitouch gesture.
2043 * Ensure that wallpaper gets the same gesture.
2044 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00002045TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002046 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002047 sp<FakeWindowHandle> foregroundWindow =
2048 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2049 foregroundWindow->setDupTouchToWallpaper(true);
2050 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002051
2052 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002053 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002054 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002055
Arthur Hungc539dbb2022-12-08 07:45:36 +00002056 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002057
2058 // Touch down on top window
2059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2060 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2061 {100, 100}))
2062 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2063
2064 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00002065 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002066 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2067
2068 // Second finger down on the top window
2069 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002070 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002071 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002072 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2073 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002074 .build();
2075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2076 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2077 InputEventInjectionSync::WAIT_FOR_RESULT))
2078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2079
Harry Cutts33476232023-01-30 19:57:29 +00002080 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
2081 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002082 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002083
2084 const MotionEvent secondFingerUpEvent =
2085 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2086 .displayId(ADISPLAY_ID_DEFAULT)
2087 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002088 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2089 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002090 .build();
2091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2092 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
2093 InputEventInjectionSync::WAIT_FOR_RESULT))
2094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2095 foregroundWindow->consumeMotionPointerUp(0);
2096 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2097
2098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08002099 injectMotionEvent(mDispatcher,
2100 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2101 AINPUT_SOURCE_TOUCHSCREEN)
2102 .displayId(ADISPLAY_ID_DEFAULT)
2103 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2104 .pointer(PointerBuilder(/* id */ 1,
2105 AMOTION_EVENT_TOOL_TYPE_FINGER)
2106 .x(100)
2107 .y(100))
2108 .build(),
2109 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2111 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2112 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002113}
2114
2115/**
2116 * Two windows: a window on the left and window on the right.
2117 * A third window, wallpaper, is behind both windows, and spans both top windows.
2118 * The first touch down goes to the left window. A second pointer touches down on the right window.
2119 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2120 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2121 * ACTION_POINTER_DOWN(1).
2122 */
2123TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2124 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2125 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002126 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002127 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002128 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002129
2130 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002131 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002132 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002133 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002134
2135 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002136 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002137 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002138 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002139
2140 mDispatcher->setInputWindows(
2141 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2142
2143 // Touch down on left window
2144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2145 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2146 {100, 100}))
2147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2148
2149 // Both foreground window and its wallpaper should receive the touch down
2150 leftWindow->consumeMotionDown();
2151 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2152
2153 // Second finger down on the right window
2154 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002155 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002156 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002157 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2158 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002159 .build();
2160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2161 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2162 InputEventInjectionSync::WAIT_FOR_RESULT))
2163 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2164
2165 leftWindow->consumeMotionMove();
2166 // Since the touch is split, right window gets ACTION_DOWN
2167 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002168 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002169 expectedWallpaperFlags);
2170
2171 // Now, leftWindow, which received the first finger, disappears.
2172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2173 leftWindow->consumeMotionCancel();
2174 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2175 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2176
2177 // The pointer that's still down on the right window moves, and goes to the right window only.
2178 // As far as the dispatcher's concerned though, both pointers are still present.
2179 const MotionEvent secondFingerMoveEvent =
2180 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2181 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002182 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2183 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002184 .build();
2185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2186 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2187 InputEventInjectionSync::WAIT_FOR_RESULT));
2188 rightWindow->consumeMotionMove();
2189
2190 leftWindow->assertNoEvents();
2191 rightWindow->assertNoEvents();
2192 wallpaperWindow->assertNoEvents();
2193}
2194
Arthur Hungc539dbb2022-12-08 07:45:36 +00002195/**
2196 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2197 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2198 * The right window should receive ACTION_DOWN.
2199 */
2200TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002201 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002202 sp<FakeWindowHandle> leftWindow =
2203 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2204 leftWindow->setFrame(Rect(0, 0, 200, 200));
2205 leftWindow->setDupTouchToWallpaper(true);
2206 leftWindow->setSlippery(true);
2207
2208 sp<FakeWindowHandle> rightWindow =
2209 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2210 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002211
2212 sp<FakeWindowHandle> wallpaperWindow =
2213 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2214 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002215
Arthur Hungc539dbb2022-12-08 07:45:36 +00002216 mDispatcher->setInputWindows(
2217 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002218
Arthur Hungc539dbb2022-12-08 07:45:36 +00002219 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2221 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002222 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002223 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002224
2225 // Both foreground window and its wallpaper should receive the touch down
2226 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002227 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2228
Arthur Hungc539dbb2022-12-08 07:45:36 +00002229 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002231 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2232 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002233 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2234
Arthur Hungc539dbb2022-12-08 07:45:36 +00002235 leftWindow->consumeMotionCancel();
2236 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2237 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002238}
2239
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002240/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002241 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2242 * interactive, it might stop sending this flag.
2243 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2244 * to have a consistent input stream.
2245 *
2246 * Test procedure:
2247 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2248 * DOWN (new gesture).
2249 *
2250 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2251 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2252 *
2253 * We technically just need a single window here, but we are using two windows (spy on top and a
2254 * regular window below) to emulate the actual situation where it happens on the device.
2255 */
2256TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2257 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2258 sp<FakeWindowHandle> spyWindow =
2259 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2260 spyWindow->setFrame(Rect(0, 0, 200, 200));
2261 spyWindow->setTrustedOverlay(true);
2262 spyWindow->setSpy(true);
2263
2264 sp<FakeWindowHandle> window =
2265 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2266 window->setFrame(Rect(0, 0, 200, 200));
2267
2268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2269 const int32_t touchDeviceId = 4;
2270 NotifyMotionArgs args;
2271
2272 // Two pointers down
2273 mDispatcher->notifyMotion(&(
2274 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2275 .deviceId(touchDeviceId)
2276 .policyFlags(DEFAULT_POLICY_FLAGS)
2277 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2278 .build()));
2279
2280 mDispatcher->notifyMotion(&(
2281 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2282 .deviceId(touchDeviceId)
2283 .policyFlags(DEFAULT_POLICY_FLAGS)
2284 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2285 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2286 .build()));
2287 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2288 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2289 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2290 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2291
2292 // Cancel the current gesture. Send the cancel without the default policy flags.
2293 mDispatcher->notifyMotion(&(
2294 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2295 .deviceId(touchDeviceId)
2296 .policyFlags(0)
2297 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2298 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2299 .build()));
2300 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2301 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2302
2303 // We don't need to reset the device to reproduce the issue, but the reset event typically
2304 // follows, so we keep it here to model the actual listener behaviour more closely.
2305 NotifyDeviceResetArgs resetArgs;
2306 resetArgs.id = 1; // arbitrary id
2307 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2308 resetArgs.deviceId = touchDeviceId;
2309 mDispatcher->notifyDeviceReset(&resetArgs);
2310
2311 // Start new gesture
2312 mDispatcher->notifyMotion(&(
2313 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2314 .deviceId(touchDeviceId)
2315 .policyFlags(DEFAULT_POLICY_FLAGS)
2316 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2317 .build()));
2318 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2319 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2320
2321 // No more events
2322 spyWindow->assertNoEvents();
2323 window->assertNoEvents();
2324}
2325
2326/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002327 * Two windows: a window on the left and a window on the right.
2328 * Mouse is hovered from the right window into the left window.
2329 * Next, we tap on the left window, where the cursor was last seen.
2330 * The second tap is done onto the right window.
2331 * The mouse and tap are from two different devices.
2332 * We technically don't need to set the downtime / eventtime for these events, but setting these
2333 * explicitly helps during debugging.
2334 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2335 * In the buggy implementation, a tap on the right window would cause a crash.
2336 */
2337TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2338 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2339 sp<FakeWindowHandle> leftWindow =
2340 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2341 leftWindow->setFrame(Rect(0, 0, 200, 200));
2342
2343 sp<FakeWindowHandle> rightWindow =
2344 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2345 rightWindow->setFrame(Rect(200, 0, 400, 200));
2346
2347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2348 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2349 // stale.
2350 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2351 const int32_t mouseDeviceId = 6;
2352 const int32_t touchDeviceId = 4;
2353 // Move the cursor from right
2354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2355 injectMotionEvent(mDispatcher,
2356 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2357 AINPUT_SOURCE_MOUSE)
2358 .deviceId(mouseDeviceId)
2359 .downTime(baseTime + 10)
2360 .eventTime(baseTime + 20)
2361 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2362 .x(300)
2363 .y(100))
2364 .build()));
2365 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2366
2367 // .. to the left window
2368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2369 injectMotionEvent(mDispatcher,
2370 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2371 AINPUT_SOURCE_MOUSE)
2372 .deviceId(mouseDeviceId)
2373 .downTime(baseTime + 10)
2374 .eventTime(baseTime + 30)
2375 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2376 .x(110)
2377 .y(100))
2378 .build()));
2379 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2380 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2381 // Now tap the left window
2382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2383 injectMotionEvent(mDispatcher,
2384 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2385 AINPUT_SOURCE_TOUCHSCREEN)
2386 .deviceId(touchDeviceId)
2387 .downTime(baseTime + 40)
2388 .eventTime(baseTime + 40)
2389 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2390 .x(100)
2391 .y(100))
2392 .build()));
2393 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2394 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2395
2396 // release tap
2397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2398 injectMotionEvent(mDispatcher,
2399 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2400 AINPUT_SOURCE_TOUCHSCREEN)
2401 .deviceId(touchDeviceId)
2402 .downTime(baseTime + 40)
2403 .eventTime(baseTime + 50)
2404 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2405 .x(100)
2406 .y(100))
2407 .build()));
2408 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2409
2410 // Tap the window on the right
2411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2412 injectMotionEvent(mDispatcher,
2413 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2414 AINPUT_SOURCE_TOUCHSCREEN)
2415 .deviceId(touchDeviceId)
2416 .downTime(baseTime + 60)
2417 .eventTime(baseTime + 60)
2418 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2419 .x(300)
2420 .y(100))
2421 .build()));
2422 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2423
2424 // release tap
2425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2426 injectMotionEvent(mDispatcher,
2427 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2428 AINPUT_SOURCE_TOUCHSCREEN)
2429 .deviceId(touchDeviceId)
2430 .downTime(baseTime + 60)
2431 .eventTime(baseTime + 70)
2432 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2433 .x(300)
2434 .y(100))
2435 .build()));
2436 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2437
2438 // No more events
2439 leftWindow->assertNoEvents();
2440 rightWindow->assertNoEvents();
2441}
2442
2443/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002444 * Two windows: a window on the left and a window on the right.
2445 * Mouse is clicked on the left window and remains down. Touch is touched on the right and remains
2446 * down. Then, on the left window, also place second touch pointer down.
2447 * This test tries to reproduce a crash.
2448 * In the buggy implementation, second pointer down on the left window would cause a crash.
2449 */
2450TEST_F(InputDispatcherTest, MultiDeviceSplitTouch) {
2451 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2452 sp<FakeWindowHandle> leftWindow =
2453 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2454 leftWindow->setFrame(Rect(0, 0, 200, 200));
2455
2456 sp<FakeWindowHandle> rightWindow =
2457 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2458 rightWindow->setFrame(Rect(200, 0, 400, 200));
2459
2460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2461
2462 const int32_t touchDeviceId = 4;
2463 const int32_t mouseDeviceId = 6;
2464 NotifyMotionArgs args;
2465
2466 // Start hovering over the left window
2467 mDispatcher->notifyMotion(&(
2468 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2469 .deviceId(mouseDeviceId)
2470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2471 .build()));
2472 leftWindow->consumeMotionEvent(
2473 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2474
2475 // Mouse down on left window
2476 mDispatcher->notifyMotion(&(
2477 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2478 .deviceId(mouseDeviceId)
2479 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2480 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2481 .build()));
2482
2483 leftWindow->consumeMotionEvent(
2484 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
2485 leftWindow->consumeMotionEvent(
2486 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2487
2488 mDispatcher->notifyMotion(&(
2489 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2490 .deviceId(mouseDeviceId)
2491 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2492 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2493 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2494 .build()));
2495 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2496
2497 // First touch pointer down on right window
2498 mDispatcher->notifyMotion(&(
2499 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2500 .deviceId(touchDeviceId)
2501 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2502 .build()));
2503 leftWindow->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2504
2505 rightWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2506
2507 // Second touch pointer down on left window
2508 mDispatcher->notifyMotion(&(
2509 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2510 .deviceId(touchDeviceId)
2511 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2512 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2513 .build()));
2514 leftWindow->consumeMotionEvent(
2515 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2516 // This MOVE event is not necessary (doesn't carry any new information), but it's there in the
2517 // current implementation.
2518 const std::map<int32_t, PointF> expectedPointers{{0, PointF{100, 100}}};
2519 rightWindow->consumeMotionEvent(
2520 AllOf(WithMotionAction(ACTION_MOVE), WithPointers(expectedPointers)));
2521
2522 leftWindow->assertNoEvents();
2523 rightWindow->assertNoEvents();
2524}
2525
2526/**
2527 * On a single window, use two different devices: mouse and touch.
2528 * Touch happens first, with two pointers going down, and then the first pointer leaving.
2529 * Mouse is clicked next, which causes the touch stream to be aborted with ACTION_CANCEL.
2530 * Finally, a second touch pointer goes down again. Ensure the second touch pointer is ignored,
2531 * because the mouse is currently down, and a POINTER_DOWN event from the touchscreen does not
2532 * represent a new gesture.
2533 */
2534TEST_F(InputDispatcherTest, MixedTouchAndMouseWithPointerDown) {
2535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2536 sp<FakeWindowHandle> window =
2537 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2538 window->setFrame(Rect(0, 0, 400, 400));
2539
2540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2541
2542 const int32_t touchDeviceId = 4;
2543 const int32_t mouseDeviceId = 6;
2544 NotifyMotionArgs args;
2545
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08002546 // First touch pointer down
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002547 mDispatcher->notifyMotion(&(
2548 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2549 .deviceId(touchDeviceId)
2550 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2551 .build()));
2552 // Second touch pointer down
2553 mDispatcher->notifyMotion(&(
2554 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2555 .deviceId(touchDeviceId)
2556 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2557 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2558 .build()));
2559 // First touch pointer lifts. The second one remains down
2560 mDispatcher->notifyMotion(&(
2561 args = MotionArgsBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2562 .deviceId(touchDeviceId)
2563 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2564 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2565 .build()));
2566 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2567 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2568 window->consumeMotionEvent(WithMotionAction(POINTER_0_UP));
2569
2570 // Mouse down. The touch should be canceled
2571 mDispatcher->notifyMotion(&(
2572 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2573 .deviceId(mouseDeviceId)
2574 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2575 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2576 .build()));
2577
2578 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
Siarhei Vishniakou82dc0422023-02-17 23:12:52 -08002579 WithPointerCount(1u)));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002580 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2581
2582 mDispatcher->notifyMotion(&(
2583 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2584 .deviceId(mouseDeviceId)
2585 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2586 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2587 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(320).y(100))
2588 .build()));
2589 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2590
2591 // Second touch pointer down.
2592 mDispatcher->notifyMotion(&(
2593 args = MotionArgsBuilder(POINTER_0_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2594 .deviceId(touchDeviceId)
2595 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2596 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(350).y(100))
2597 .build()));
2598 // The pointer_down event should be ignored
2599 window->assertNoEvents();
2600}
2601
2602/**
Siarhei Vishniakou56e79092023-02-21 19:13:16 -08002603 * Inject a touch down and then send a new event via 'notifyMotion'. Ensure the new event cancels
2604 * the injected event.
2605 */
2606TEST_F(InputDispatcherTest, UnfinishedInjectedEvent) {
2607 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2608 sp<FakeWindowHandle> window =
2609 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2610 window->setFrame(Rect(0, 0, 400, 400));
2611
2612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2613
2614 const int32_t touchDeviceId = 4;
2615 NotifyMotionArgs args;
2616 // Pretend a test injects an ACTION_DOWN mouse event, but forgets to lift up the touch after
2617 // completion.
2618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2619 injectMotionEvent(mDispatcher,
2620 MotionEventBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2621 .deviceId(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID)
2622 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2623 .x(50)
2624 .y(50))
2625 .build()));
2626 window->consumeMotionEvent(
2627 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2628
2629 // Now a real touch comes. Rather than crashing or dropping the real event, the injected pointer
2630 // should be canceled and the new gesture should take over.
2631 mDispatcher->notifyMotion(&(
2632 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2633 .deviceId(touchDeviceId)
2634 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
2635 .build()));
2636
2637 window->consumeMotionEvent(
2638 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(VIRTUAL_KEYBOARD_ID)));
2639 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
2640}
2641
2642/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002643 * This test is similar to the test above, but the sequence of injected events is different.
2644 *
2645 * Two windows: a window on the left and a window on the right.
2646 * Mouse is hovered over the left window.
2647 * Next, we tap on the left window, where the cursor was last seen.
2648 *
2649 * After that, we inject one finger down onto the right window, and then a second finger down onto
2650 * the left window.
2651 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2652 * window (first), and then another on the left window (second).
2653 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2654 * In the buggy implementation, second finger down on the left window would cause a crash.
2655 */
2656TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2657 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2658 sp<FakeWindowHandle> leftWindow =
2659 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2660 leftWindow->setFrame(Rect(0, 0, 200, 200));
2661
2662 sp<FakeWindowHandle> rightWindow =
2663 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2664 rightWindow->setFrame(Rect(200, 0, 400, 200));
2665
2666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2667
2668 const int32_t mouseDeviceId = 6;
2669 const int32_t touchDeviceId = 4;
2670 // Hover over the left window. Keep the cursor there.
2671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2672 injectMotionEvent(mDispatcher,
2673 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2674 AINPUT_SOURCE_MOUSE)
2675 .deviceId(mouseDeviceId)
2676 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2677 .x(50)
2678 .y(50))
2679 .build()));
2680 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2681
2682 // Tap on left window
2683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2684 injectMotionEvent(mDispatcher,
2685 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2686 AINPUT_SOURCE_TOUCHSCREEN)
2687 .deviceId(touchDeviceId)
2688 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2689 .x(100)
2690 .y(100))
2691 .build()));
2692
2693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2694 injectMotionEvent(mDispatcher,
2695 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2696 AINPUT_SOURCE_TOUCHSCREEN)
2697 .deviceId(touchDeviceId)
2698 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2699 .x(100)
2700 .y(100))
2701 .build()));
2702 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2703 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2704 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2705
2706 // First finger down on right window
2707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2708 injectMotionEvent(mDispatcher,
2709 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2710 AINPUT_SOURCE_TOUCHSCREEN)
2711 .deviceId(touchDeviceId)
2712 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2713 .x(300)
2714 .y(100))
2715 .build()));
2716 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2717
2718 // Second finger down on the left window
2719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2720 injectMotionEvent(mDispatcher,
2721 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2722 .deviceId(touchDeviceId)
2723 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2724 .x(300)
2725 .y(100))
2726 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2727 .x(100)
2728 .y(100))
2729 .build()));
2730 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2731 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2732
2733 // No more events
2734 leftWindow->assertNoEvents();
2735 rightWindow->assertNoEvents();
2736}
2737
2738/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002739 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2740 * While the touch is down, new hover events from the stylus device should be ignored. After the
2741 * touch is gone, stylus hovering should start working again.
2742 */
2743TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2745 sp<FakeWindowHandle> window =
2746 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2747 window->setFrame(Rect(0, 0, 200, 200));
2748
2749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2750
2751 const int32_t stylusDeviceId = 5;
2752 const int32_t touchDeviceId = 4;
2753 // Start hovering with stylus
2754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2755 injectMotionEvent(mDispatcher,
2756 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2757 AINPUT_SOURCE_STYLUS)
2758 .deviceId(stylusDeviceId)
2759 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2760 .x(50)
2761 .y(50))
2762 .build()));
2763 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2764
2765 // Finger down on the window
2766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2767 injectMotionEvent(mDispatcher,
2768 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2769 AINPUT_SOURCE_TOUCHSCREEN)
2770 .deviceId(touchDeviceId)
2771 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2772 .x(100)
2773 .y(100))
2774 .build()));
2775 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2776 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2777
2778 // Try to continue hovering with stylus. Since we are already down, injection should fail
2779 ASSERT_EQ(InputEventInjectionResult::FAILED,
2780 injectMotionEvent(mDispatcher,
2781 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2782 AINPUT_SOURCE_STYLUS)
2783 .deviceId(stylusDeviceId)
2784 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2785 .x(50)
2786 .y(50))
2787 .build()));
2788 // No event should be sent. This event should be ignored because a pointer from another device
2789 // is already down.
2790
2791 // Lift up the finger
2792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2793 injectMotionEvent(mDispatcher,
2794 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2795 AINPUT_SOURCE_TOUCHSCREEN)
2796 .deviceId(touchDeviceId)
2797 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2798 .x(100)
2799 .y(100))
2800 .build()));
2801 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2802
2803 // Now that the touch is gone, stylus hovering should start working again
2804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2805 injectMotionEvent(mDispatcher,
2806 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2807 AINPUT_SOURCE_STYLUS)
2808 .deviceId(stylusDeviceId)
2809 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2810 .x(50)
2811 .y(50))
2812 .build()));
2813 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2814 // No more events
2815 window->assertNoEvents();
2816}
2817
2818/**
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002819 * A spy window above a window with no input channel.
2820 * Start hovering with a stylus device, and then tap with it.
2821 * Ensure spy window receives the entire sequence.
2822 */
2823TEST_F(InputDispatcherTest, StylusHoverAndDownNoInputChannel) {
2824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2825 sp<FakeWindowHandle> spyWindow =
2826 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2827 spyWindow->setFrame(Rect(0, 0, 200, 200));
2828 spyWindow->setTrustedOverlay(true);
2829 spyWindow->setSpy(true);
2830 sp<FakeWindowHandle> window =
2831 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2832 window->setNoInputChannel(true);
2833 window->setFrame(Rect(0, 0, 200, 200));
2834
2835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2836
2837 NotifyMotionArgs args;
2838
2839 // Start hovering with stylus
2840 mDispatcher->notifyMotion(
2841 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2842 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2843 .build()));
2844 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2845 // Stop hovering
2846 mDispatcher->notifyMotion(
2847 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2848 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2849 .build()));
2850 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2851
2852 // Stylus touches down
2853 mDispatcher->notifyMotion(
2854 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_STYLUS)
2855 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2856 .build()));
2857 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2858
2859 // Stylus goes up
2860 mDispatcher->notifyMotion(
2861 &(args = MotionArgsBuilder(ACTION_UP, AINPUT_SOURCE_STYLUS)
2862 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2863 .build()));
2864 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_UP));
2865
2866 // Again hover
2867 mDispatcher->notifyMotion(
2868 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
2869 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2870 .build()));
2871 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_ENTER));
2872 // Stop hovering
2873 mDispatcher->notifyMotion(
2874 &(args = MotionArgsBuilder(ACTION_HOVER_EXIT, AINPUT_SOURCE_STYLUS)
2875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS).x(50).y(50))
2876 .build()));
2877 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2878
2879 // No more events
2880 spyWindow->assertNoEvents();
2881 window->assertNoEvents();
2882}
2883
2884/**
2885 * Start hovering with a mouse, and then tap with a touch device. Pilfer the touch stream.
2886 * Next, click with the mouse device. Both windows (spy and regular) should receive the new mouse
2887 * ACTION_DOWN event because that's a new gesture, and pilfering should no longer be active.
2888 * While the mouse is down, new move events from the touch device should be ignored.
2889 */
2890TEST_F(InputDispatcherTest, TouchPilferAndMouseMove) {
2891 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2892 sp<FakeWindowHandle> spyWindow =
2893 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2894 spyWindow->setFrame(Rect(0, 0, 200, 200));
2895 spyWindow->setTrustedOverlay(true);
2896 spyWindow->setSpy(true);
2897 sp<FakeWindowHandle> window =
2898 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2899 window->setFrame(Rect(0, 0, 200, 200));
2900
2901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2902
2903 const int32_t mouseDeviceId = 7;
2904 const int32_t touchDeviceId = 4;
2905 NotifyMotionArgs args;
2906
2907 // Hover a bit with mouse first
2908 mDispatcher->notifyMotion(&(
2909 args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
2910 .deviceId(mouseDeviceId)
2911 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2912 .build()));
2913 spyWindow->consumeMotionEvent(
2914 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2915 window->consumeMotionEvent(
2916 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
2917
2918 // Start touching
2919 mDispatcher->notifyMotion(
2920 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2921 .deviceId(touchDeviceId)
2922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2923 .build()));
2924 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2925 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
2926 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2927 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
2928
2929 mDispatcher->notifyMotion(
2930 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2931 .deviceId(touchDeviceId)
2932 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(55).y(55))
2933 .build()));
2934 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2935 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2936
2937 // Pilfer the stream
2938 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2939 window->consumeMotionEvent(WithMotionAction(ACTION_CANCEL));
2940
2941 mDispatcher->notifyMotion(
2942 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2943 .deviceId(touchDeviceId)
2944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
2945 .build()));
2946 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2947
2948 // Mouse down
2949 mDispatcher->notifyMotion(&(
2950 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2951 .deviceId(mouseDeviceId)
2952 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2953 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2954 .build()));
2955
2956 spyWindow->consumeMotionEvent(
2957 AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId)));
2958 spyWindow->consumeMotionEvent(
2959 AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2960 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
2961
2962 mDispatcher->notifyMotion(&(
2963 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
2964 .deviceId(mouseDeviceId)
2965 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2966 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2967 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(100).y(100))
2968 .build()));
2969 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2970 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
2971
2972 // Mouse move!
2973 mDispatcher->notifyMotion(&(
2974 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_MOUSE)
2975 .deviceId(mouseDeviceId)
2976 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(110).y(110))
2978 .build()));
2979 spyWindow->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2980 window->consumeMotionEvent(WithMotionAction(ACTION_MOVE));
2981
2982 // Touch move!
2983 mDispatcher->notifyMotion(
2984 &(args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2985 .deviceId(touchDeviceId)
2986 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(65).y(65))
2987 .build()));
2988
2989 // No more events
2990 spyWindow->assertNoEvents();
2991 window->assertNoEvents();
2992}
2993
2994/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002995 * On the display, have a single window, and also an area where there's no window.
2996 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2997 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2998 */
2999TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
3000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3001 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003002 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003003
3004 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
3005 NotifyMotionArgs args;
3006
3007 // Touch down on the empty space
3008 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
3009
3010 mDispatcher->waitForIdle();
3011 window->assertNoEvents();
3012
3013 // Now touch down on the window with another pointer
3014 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
3015 mDispatcher->waitForIdle();
3016 window->consumeMotionDown();
3017}
3018
3019/**
3020 * Same test as above, but instead of touching the empty space, the first touch goes to
3021 * non-touchable window.
3022 */
3023TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
3024 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3025 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003026 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003027 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3028 window1->setTouchable(false);
3029 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003030 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003031 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3032
3033 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3034
3035 NotifyMotionArgs args;
3036 // Touch down on the non-touchable window
3037 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3038
3039 mDispatcher->waitForIdle();
3040 window1->assertNoEvents();
3041 window2->assertNoEvents();
3042
3043 // Now touch down on the window with another pointer
3044 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3045 mDispatcher->waitForIdle();
3046 window2->consumeMotionDown();
3047}
3048
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003049/**
3050 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
3051 * to the event time of the first ACTION_DOWN sent to the particular window.
3052 */
3053TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
3054 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3055 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003056 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003057 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
3058 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003059 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003060 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
3061
3062 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
3063
3064 NotifyMotionArgs args;
3065 // Touch down on the first window
3066 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
3067
3068 mDispatcher->waitForIdle();
3069 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003070 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003071 window2->assertNoEvents();
3072 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
3073 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
3074 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
3075
3076 // Now touch down on the window with another pointer
3077 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
3078 mDispatcher->waitForIdle();
3079 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003080 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003081 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
3082 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
3083 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
3084 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
3085
3086 // Now move the pointer on the second window
3087 mDispatcher->notifyMotion(
3088 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
3089 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003090 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003091
3092 // Now add new touch down on the second window
3093 mDispatcher->notifyMotion(
3094 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
3095 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003096 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003097
3098 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
3099 window1->consumeMotionMove();
3100 window1->assertNoEvents();
3101
3102 // Now move the pointer on the first window
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08003103 mDispatcher->notifyMotion(&(
3104 args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}, {150, 50}})));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003105 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003106 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003107
3108 mDispatcher->notifyMotion(&(
3109 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
3110 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08003111 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003112}
3113
Garfield Tandf26e862020-07-01 20:18:19 -07003114TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003116 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003117 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003118 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003119 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003120 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003121 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003122
3123 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3124
3125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
3126
3127 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003129 injectMotionEvent(mDispatcher,
3130 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3131 AINPUT_SOURCE_MOUSE)
3132 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3133 .x(900)
3134 .y(400))
3135 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003136 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003137
3138 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003140 injectMotionEvent(mDispatcher,
3141 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3142 AINPUT_SOURCE_MOUSE)
3143 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3144 .x(300)
3145 .y(400))
3146 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003147 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3148 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003149
3150 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003152 injectMotionEvent(mDispatcher,
3153 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3154 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3155 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3156 .x(300)
3157 .y(400))
3158 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003159 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3160 windowLeft->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003161
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003163 injectMotionEvent(mDispatcher,
3164 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3165 AINPUT_SOURCE_MOUSE)
3166 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3167 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3168 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3169 .x(300)
3170 .y(400))
3171 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003172 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003174 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003175 injectMotionEvent(mDispatcher,
3176 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3177 AINPUT_SOURCE_MOUSE)
3178 .buttonState(0)
3179 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3180 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3181 .x(300)
3182 .y(400))
3183 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003184 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003187 injectMotionEvent(mDispatcher,
3188 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3189 .buttonState(0)
3190 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3191 .x(300)
3192 .y(400))
3193 .build()));
3194 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3195
3196 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003198 injectMotionEvent(mDispatcher,
3199 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3200 AINPUT_SOURCE_MOUSE)
3201 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3202 .x(900)
3203 .y(400))
3204 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003205 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003206
3207 // No more events
3208 windowLeft->assertNoEvents();
3209 windowRight->assertNoEvents();
3210}
3211
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003212/**
3213 * Put two fingers down (and don't release them) and click the mouse button.
3214 * The clicking of mouse is a new ACTION_DOWN event. Since it's from a different device, the
3215 * currently active gesture should be canceled, and the new one should proceed.
3216 */
3217TEST_F(InputDispatcherTest, TwoPointersDownMouseClick) {
3218 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3219 sp<FakeWindowHandle> window =
3220 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3221 window->setFrame(Rect(0, 0, 600, 800));
3222
3223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3224
3225 const int32_t touchDeviceId = 4;
3226 const int32_t mouseDeviceId = 6;
3227 NotifyMotionArgs args;
3228
3229 // Two pointers down
3230 mDispatcher->notifyMotion(&(
3231 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3232 .deviceId(touchDeviceId)
3233 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3234 .build()));
3235
3236 mDispatcher->notifyMotion(&(
3237 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3238 .deviceId(touchDeviceId)
3239 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
3240 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
3241 .build()));
3242 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
3243 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
3244
3245 // Inject a series of mouse events for a mouse click
3246 mDispatcher->notifyMotion(&(
3247 args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3248 .deviceId(mouseDeviceId)
3249 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3250 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3251 .build()));
3252 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDeviceId(touchDeviceId),
3253 WithPointerCount(2u)));
3254 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(mouseDeviceId)));
3255
3256 mDispatcher->notifyMotion(&(
3257 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS, AINPUT_SOURCE_MOUSE)
3258 .deviceId(mouseDeviceId)
3259 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3260 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3261 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(300).y(400))
3262 .build()));
3263 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
3264
3265 // Try to send more touch events while the mouse is down. Since it's a continuation of an
3266 // already canceled gesture, it should be ignored.
3267 mDispatcher->notifyMotion(&(
3268 args = MotionArgsBuilder(ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
3269 .deviceId(touchDeviceId)
3270 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(101).y(101))
3271 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(121).y(121))
3272 .build()));
3273 window->assertNoEvents();
3274}
3275
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003276TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
3277 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3278
3279 sp<FakeWindowHandle> spyWindow =
3280 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3281 spyWindow->setFrame(Rect(0, 0, 600, 800));
3282 spyWindow->setTrustedOverlay(true);
3283 spyWindow->setSpy(true);
3284 sp<FakeWindowHandle> window =
3285 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3286 window->setFrame(Rect(0, 0, 600, 800));
3287
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3290
3291 // Send mouse cursor to the window
3292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3293 injectMotionEvent(mDispatcher,
3294 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3295 AINPUT_SOURCE_MOUSE)
3296 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3297 .x(100)
3298 .y(100))
3299 .build()));
3300
3301 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3302 WithSource(AINPUT_SOURCE_MOUSE)));
3303 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3304 WithSource(AINPUT_SOURCE_MOUSE)));
3305
3306 window->assertNoEvents();
3307 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003308}
3309
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003310TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
3311 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3312
3313 sp<FakeWindowHandle> spyWindow =
3314 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
3315 spyWindow->setFrame(Rect(0, 0, 600, 800));
3316 spyWindow->setTrustedOverlay(true);
3317 spyWindow->setSpy(true);
3318 sp<FakeWindowHandle> window =
3319 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3320 window->setFrame(Rect(0, 0, 600, 800));
3321
3322 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
3324
3325 // Send mouse cursor to the window
3326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3327 injectMotionEvent(mDispatcher,
3328 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3329 AINPUT_SOURCE_MOUSE)
3330 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3331 .x(100)
3332 .y(100))
3333 .build()));
3334
3335 // Move mouse cursor
3336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3337 injectMotionEvent(mDispatcher,
3338 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3339 AINPUT_SOURCE_MOUSE)
3340 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3341 .x(110)
3342 .y(110))
3343 .build()));
3344
3345 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3346 WithSource(AINPUT_SOURCE_MOUSE)));
3347 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3348 WithSource(AINPUT_SOURCE_MOUSE)));
3349 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3350 WithSource(AINPUT_SOURCE_MOUSE)));
3351 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3352 WithSource(AINPUT_SOURCE_MOUSE)));
3353 // Touch down on the window
3354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3355 injectMotionEvent(mDispatcher,
3356 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3357 AINPUT_SOURCE_TOUCHSCREEN)
3358 .deviceId(SECOND_DEVICE_ID)
3359 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3360 .x(200)
3361 .y(200))
3362 .build()));
3363 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3364 WithSource(AINPUT_SOURCE_MOUSE)));
3365 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3366 WithSource(AINPUT_SOURCE_MOUSE)));
3367 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3368 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3369 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3370 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3371
3372 // pilfer the motion, retaining the gesture on the spy window.
3373 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
3374 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3375 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3376
3377 // Touch UP on the window
3378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3379 injectMotionEvent(mDispatcher,
3380 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3381 AINPUT_SOURCE_TOUCHSCREEN)
3382 .deviceId(SECOND_DEVICE_ID)
3383 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3384 .x(200)
3385 .y(200))
3386 .build()));
3387 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3388 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3389
3390 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
3391 // to send a new gesture. It should again go to both windows (spy and the window below), just
3392 // like the first gesture did, before pilfering. The window configuration has not changed.
3393
3394 // One more tap - DOWN
3395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3396 injectMotionEvent(mDispatcher,
3397 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
3398 AINPUT_SOURCE_TOUCHSCREEN)
3399 .deviceId(SECOND_DEVICE_ID)
3400 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3401 .x(250)
3402 .y(250))
3403 .build()));
3404 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3405 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3406 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3407 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3408
3409 // Touch UP on the window
3410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3411 injectMotionEvent(mDispatcher,
3412 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
3413 AINPUT_SOURCE_TOUCHSCREEN)
3414 .deviceId(SECOND_DEVICE_ID)
3415 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3416 .x(250)
3417 .y(250))
3418 .build()));
3419 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3420 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3421 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3422 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
3423
3424 window->assertNoEvents();
3425 spyWindow->assertNoEvents();
3426}
3427
Garfield Tandf26e862020-07-01 20:18:19 -07003428// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
3429// directly in this test.
3430TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07003431 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07003432 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003433 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07003434 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07003435
3436 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3437
3438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003441 injectMotionEvent(mDispatcher,
3442 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3443 AINPUT_SOURCE_MOUSE)
3444 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3445 .x(300)
3446 .y(400))
3447 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003448 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07003449 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003451 injectMotionEvent(mDispatcher,
3452 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3453 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3454 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3455 .x(300)
3456 .y(400))
3457 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003458 window->consumeMotionEvent(WithMotionAction(ACTION_HOVER_EXIT));
3459 window->consumeMotionEvent(WithMotionAction(ACTION_DOWN));
Garfield Tandf26e862020-07-01 20:18:19 -07003460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003462 injectMotionEvent(mDispatcher,
3463 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
3464 AINPUT_SOURCE_MOUSE)
3465 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
3466 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3467 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3468 .x(300)
3469 .y(400))
3470 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003471 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07003472
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003474 injectMotionEvent(mDispatcher,
3475 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
3476 AINPUT_SOURCE_MOUSE)
3477 .buttonState(0)
3478 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
3479 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3480 .x(300)
3481 .y(400))
3482 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003483 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07003484
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003486 injectMotionEvent(mDispatcher,
3487 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
3488 .buttonState(0)
3489 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3490 .x(300)
3491 .y(400))
3492 .build()));
3493 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
3494
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003495 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07003496 injectMotionEvent(mDispatcher,
3497 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
3498 AINPUT_SOURCE_MOUSE)
3499 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3500 .x(300)
3501 .y(400))
3502 .build()));
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08003503 window->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07003504}
3505
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003506/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003507 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
3508 * is generated.
3509 */
3510TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
3511 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3512 sp<FakeWindowHandle> window =
3513 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3514 window->setFrame(Rect(0, 0, 1200, 800));
3515
3516 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3517
3518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3519
3520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3521 injectMotionEvent(mDispatcher,
3522 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3523 AINPUT_SOURCE_MOUSE)
3524 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3525 .x(300)
3526 .y(400))
3527 .build()));
3528 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3529
3530 // Remove the window, but keep the channel.
3531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3532 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3533}
3534
3535/**
Siarhei Vishniakou4e1ffa52023-02-21 11:50:34 -08003536 * If mouse is hovering when the touch goes down, the hovering should be stopped via HOVER_EXIT.
3537 */
3538TEST_F(InputDispatcherTest, TouchDownAfterMouseHover) {
3539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3540 sp<FakeWindowHandle> window =
3541 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3542 window->setFrame(Rect(0, 0, 100, 100));
3543
3544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3545
3546 const int32_t mouseDeviceId = 7;
3547 const int32_t touchDeviceId = 4;
3548 NotifyMotionArgs args;
3549
3550 // Start hovering with the mouse
3551 mDispatcher->notifyMotion(
3552 &(args = MotionArgsBuilder(ACTION_HOVER_ENTER, AINPUT_SOURCE_MOUSE)
3553 .deviceId(mouseDeviceId)
3554 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE).x(10).y(10))
3555 .build()));
3556 window->consumeMotionEvent(
3557 AllOf(WithMotionAction(ACTION_HOVER_ENTER), WithDeviceId(mouseDeviceId)));
3558
3559 // Touch goes down
3560 mDispatcher->notifyMotion(
3561 &(args = MotionArgsBuilder(ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3562 .deviceId(touchDeviceId)
3563 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3564 .build()));
3565
3566 window->consumeMotionEvent(
3567 AllOf(WithMotionAction(ACTION_HOVER_EXIT), WithDeviceId(mouseDeviceId)));
3568 window->consumeMotionEvent(AllOf(WithMotionAction(ACTION_DOWN), WithDeviceId(touchDeviceId)));
3569}
3570
3571/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003572 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003573 * The tap causes a HOVER_EXIT event to be generated because the current event
3574 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003575 */
3576TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3577 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3578 sp<FakeWindowHandle> window =
3579 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3580 window->setFrame(Rect(0, 0, 100, 100));
3581
3582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3583
3584 // Inject a hover_move from mouse.
3585 NotifyMotionArgs motionArgs =
3586 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3587 ADISPLAY_ID_DEFAULT, {{50, 50}});
3588 motionArgs.xCursorPosition = 50;
3589 motionArgs.yCursorPosition = 50;
3590 mDispatcher->notifyMotion(&motionArgs);
3591 ASSERT_NO_FATAL_FAILURE(
3592 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3593 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003594
3595 // Tap on the window
3596 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3597 ADISPLAY_ID_DEFAULT, {{10, 10}});
3598 mDispatcher->notifyMotion(&motionArgs);
3599 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003600 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3601 WithSource(AINPUT_SOURCE_MOUSE))));
3602
3603 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003604 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3605 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3606
3607 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3608 ADISPLAY_ID_DEFAULT, {{10, 10}});
3609 mDispatcher->notifyMotion(&motionArgs);
3610 ASSERT_NO_FATAL_FAILURE(
3611 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3612 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3613}
3614
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003615TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3617 sp<FakeWindowHandle> windowDefaultDisplay =
3618 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3619 ADISPLAY_ID_DEFAULT);
3620 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3621 sp<FakeWindowHandle> windowSecondDisplay =
3622 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3623 SECOND_DISPLAY_ID);
3624 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3625
3626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3627 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3628
3629 // Set cursor position in window in default display and check that hover enter and move
3630 // events are generated.
3631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3632 injectMotionEvent(mDispatcher,
3633 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3634 AINPUT_SOURCE_MOUSE)
3635 .displayId(ADISPLAY_ID_DEFAULT)
3636 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3637 .x(300)
3638 .y(600))
3639 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003640 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003641
3642 // Remove all windows in secondary display and check that no event happens on window in
3643 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003644 mDispatcher->setInputWindows(
3645 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003646 windowDefaultDisplay->assertNoEvents();
3647
3648 // Move cursor position in window in default display and check that only hover move
3649 // event is generated and not hover enter event.
3650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3651 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3653 injectMotionEvent(mDispatcher,
3654 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3655 AINPUT_SOURCE_MOUSE)
3656 .displayId(ADISPLAY_ID_DEFAULT)
3657 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3658 .x(400)
3659 .y(700))
3660 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003661 windowDefaultDisplay->consumeMotionEvent(
3662 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3663 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003664 windowDefaultDisplay->assertNoEvents();
3665}
3666
Garfield Tan00f511d2019-06-12 16:55:40 -07003667TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003669
3670 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003671 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003672 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003673 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003674 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003675 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003676
3677 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3678
Arthur Hung72d8dc32020-03-28 00:48:39 +00003679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003680
3681 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3682 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003684 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003685 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003686 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003687 windowRight->assertNoEvents();
3688}
3689
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003690TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003691 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003692 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3693 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003694 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003695
Arthur Hung72d8dc32020-03-28 00:48:39 +00003696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003697 setFocusedWindow(window);
3698
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003699 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003700
3701 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3702 mDispatcher->notifyKey(&keyArgs);
3703
3704 // Window should receive key down event.
3705 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3706
3707 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3708 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003709 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003710 mDispatcher->notifyDeviceReset(&args);
3711 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3712 AKEY_EVENT_FLAG_CANCELED);
3713}
3714
3715TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003716 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003717 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3718 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003719
Arthur Hung72d8dc32020-03-28 00:48:39 +00003720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003721
3722 NotifyMotionArgs motionArgs =
3723 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3724 ADISPLAY_ID_DEFAULT);
3725 mDispatcher->notifyMotion(&motionArgs);
3726
3727 // Window should receive motion down event.
3728 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3729
3730 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3731 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003732 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003733 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003734 window->consumeMotionEvent(
3735 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003736}
3737
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003738TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003740 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3741 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003742 window->setFocusable(true);
3743
3744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3745 setFocusedWindow(window);
3746
3747 window->consumeFocusEvent(true);
3748
3749 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3750 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3751 const nsecs_t injectTime = keyArgs.eventTime;
3752 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3753 mDispatcher->notifyKey(&keyArgs);
3754 // The dispatching time should be always greater than or equal to intercept key timeout.
3755 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3756 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3757 std::chrono::nanoseconds(interceptKeyTimeout).count());
3758}
3759
3760TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003762 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3763 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003764 window->setFocusable(true);
3765
3766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3767 setFocusedWindow(window);
3768
3769 window->consumeFocusEvent(true);
3770
3771 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3772 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3773 mFakePolicy->setInterceptKeyTimeout(150ms);
3774 mDispatcher->notifyKey(&keyDown);
3775 mDispatcher->notifyKey(&keyUp);
3776
3777 // Window should receive key event immediately when same key up.
3778 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3779 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3780}
3781
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003782/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003783 * Two windows. First is a regular window. Second does not overlap with the first, and has
3784 * WATCH_OUTSIDE_TOUCH.
3785 * Both windows are owned by the same UID.
3786 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3787 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3788 */
3789TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3790 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3791 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3792 "First Window", ADISPLAY_ID_DEFAULT);
3793 window->setFrame(Rect{0, 0, 100, 100});
3794
3795 sp<FakeWindowHandle> outsideWindow =
3796 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3797 ADISPLAY_ID_DEFAULT);
3798 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3799 outsideWindow->setWatchOutsideTouch(true);
3800 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3802
3803 // Tap on first window.
3804 NotifyMotionArgs motionArgs =
3805 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3806 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3807 mDispatcher->notifyMotion(&motionArgs);
3808 window->consumeMotionDown();
3809 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3810 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3811 outsideWindow->consumeMotionEvent(
3812 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3813}
3814
3815/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003816 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3817 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3818 * ACTION_OUTSIDE event is sent per gesture.
3819 */
3820TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3821 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003823 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3824 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003825 window->setWatchOutsideTouch(true);
3826 window->setFrame(Rect{0, 0, 100, 100});
3827 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003828 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3829 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003830 secondWindow->setFrame(Rect{100, 100, 200, 200});
3831 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003832 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3833 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003834 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3836
3837 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3838 NotifyMotionArgs motionArgs =
3839 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3840 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3841 mDispatcher->notifyMotion(&motionArgs);
3842 window->assertNoEvents();
3843 secondWindow->assertNoEvents();
3844
3845 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3846 // Now, `window` should get ACTION_OUTSIDE.
3847 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3848 {PointF{-10, -10}, PointF{105, 105}});
3849 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003850 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3851 window->consumeMotionEvent(
3852 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003853 secondWindow->consumeMotionDown();
3854 thirdWindow->assertNoEvents();
3855
3856 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3857 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3858 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3859 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3860 mDispatcher->notifyMotion(&motionArgs);
3861 window->assertNoEvents();
3862 secondWindow->consumeMotionMove();
3863 thirdWindow->consumeMotionDown();
3864}
3865
Prabir Pradhan814fe082022-07-22 20:22:18 +00003866TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003868 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3869 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003870 window->setFocusable(true);
3871
3872 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3873 setFocusedWindow(window);
3874
3875 window->consumeFocusEvent(true);
3876
3877 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3878 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3879 mDispatcher->notifyKey(&keyDown);
3880 mDispatcher->notifyKey(&keyUp);
3881
3882 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3883 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3884
3885 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3886 mDispatcher->onWindowInfosChanged({}, {});
3887
3888 window->consumeFocusEvent(false);
3889
3890 mDispatcher->notifyKey(&keyDown);
3891 mDispatcher->notifyKey(&keyUp);
3892 window->assertNoEvents();
3893}
3894
Arthur Hung96483742022-11-15 03:30:48 +00003895TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3897 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3898 "Fake Window", ADISPLAY_ID_DEFAULT);
3899 // Ensure window is non-split and have some transform.
3900 window->setPreventSplitting(true);
3901 window->setWindowOffset(20, 40);
3902 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3903
3904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3906 {50, 50}))
3907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3908 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3909
3910 const MotionEvent secondFingerDownEvent =
3911 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3912 .displayId(ADISPLAY_ID_DEFAULT)
3913 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003914 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3915 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003916 .build();
3917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3918 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3919 InputEventInjectionSync::WAIT_FOR_RESULT))
3920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3921
3922 const MotionEvent* event = window->consumeMotion();
3923 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3924 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3925 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3926 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3927 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3928}
3929
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003930/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003931 * Ensure the correct coordinate spaces are used by InputDispatcher.
3932 *
3933 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3934 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3935 * space.
3936 */
3937class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3938public:
3939 void SetUp() override {
3940 InputDispatcherTest::SetUp();
3941 mDisplayInfos.clear();
3942 mWindowInfos.clear();
3943 }
3944
3945 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3946 gui::DisplayInfo info;
3947 info.displayId = displayId;
3948 info.transform = transform;
3949 mDisplayInfos.push_back(std::move(info));
3950 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3951 }
3952
3953 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3954 mWindowInfos.push_back(*windowHandle->getInfo());
3955 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3956 }
3957
3958 // Set up a test scenario where the display has a scaled projection and there are two windows
3959 // on the display.
3960 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3961 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3962 // respectively.
3963 ui::Transform displayTransform;
3964 displayTransform.set(2, 0, 0, 4);
3965 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3966
3967 std::shared_ptr<FakeApplicationHandle> application =
3968 std::make_shared<FakeApplicationHandle>();
3969
3970 // Add two windows to the display. Their frames are represented in the display space.
3971 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003972 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3973 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003974 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3975 addWindow(firstWindow);
3976
3977 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003978 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3979 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003980 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3981 addWindow(secondWindow);
3982 return {std::move(firstWindow), std::move(secondWindow)};
3983 }
3984
3985private:
3986 std::vector<gui::DisplayInfo> mDisplayInfos;
3987 std::vector<gui::WindowInfo> mWindowInfos;
3988};
3989
3990TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3991 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3992 // Send down to the first window. The point is represented in the display space. The point is
3993 // selected so that if the hit test was done with the transform applied to it, then it would
3994 // end up in the incorrect window.
3995 NotifyMotionArgs downMotionArgs =
3996 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3997 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3998 mDispatcher->notifyMotion(&downMotionArgs);
3999
4000 firstWindow->consumeMotionDown();
4001 secondWindow->assertNoEvents();
4002}
4003
4004// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
4005// the event should be treated as being in the logical display space.
4006TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
4007 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4008 // Send down to the first window. The point is represented in the logical display space. The
4009 // point is selected so that if the hit test was done in logical display space, then it would
4010 // end up in the incorrect window.
4011 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4012 PointF{75 * 2, 55 * 4});
4013
4014 firstWindow->consumeMotionDown();
4015 secondWindow->assertNoEvents();
4016}
4017
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004018// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
4019// event should be treated as being in the logical display space.
4020TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
4021 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4022
4023 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
4024 ui::Transform injectedEventTransform;
4025 injectedEventTransform.set(matrix);
4026 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
4027 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
4028
4029 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
4030 .displayId(ADISPLAY_ID_DEFAULT)
4031 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00004032 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004033 .x(untransformedPoint.x)
4034 .y(untransformedPoint.y))
4035 .build();
4036 event.transform(matrix);
4037
4038 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
4039 InputEventInjectionSync::WAIT_FOR_RESULT);
4040
4041 firstWindow->consumeMotionDown();
4042 secondWindow->assertNoEvents();
4043}
4044
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07004045TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
4046 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4047
4048 // Send down to the second window.
4049 NotifyMotionArgs downMotionArgs =
4050 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4051 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
4052 mDispatcher->notifyMotion(&downMotionArgs);
4053
4054 firstWindow->assertNoEvents();
4055 const MotionEvent* event = secondWindow->consumeMotion();
4056 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
4057
4058 // Ensure that the events from the "getRaw" API are in logical display coordinates.
4059 EXPECT_EQ(300, event->getRawX(0));
4060 EXPECT_EQ(880, event->getRawY(0));
4061
4062 // Ensure that the x and y values are in the window's coordinate space.
4063 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
4064 // the logical display space. This will be the origin of the window space.
4065 EXPECT_EQ(100, event->getX(0));
4066 EXPECT_EQ(80, event->getY(0));
4067}
4068
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004069using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
4070 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004071
4072class TransferTouchFixture : public InputDispatcherTest,
4073 public ::testing::WithParamInterface<TransferFunction> {};
4074
4075TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07004076 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004077
4078 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004079 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004080 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4081 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004082 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004083 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004084 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4085 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004086 sp<FakeWindowHandle> wallpaper =
4087 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
4088 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004089 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00004090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091
4092 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004093 NotifyMotionArgs downMotionArgs =
4094 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4095 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004097
Svet Ganov5d3bc372020-01-26 23:11:07 -08004098 // Only the first window should get the down event
4099 firstWindow->consumeMotionDown();
4100 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004101 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004102
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004103 // Transfer touch to the second window
4104 TransferFunction f = GetParam();
4105 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4106 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004107 // The first window gets cancel and the second gets down
4108 firstWindow->consumeMotionCancel();
4109 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004110 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004111
4112 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004113 NotifyMotionArgs upMotionArgs =
4114 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4115 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004116 mDispatcher->notifyMotion(&upMotionArgs);
4117 // The first window gets no events and the second gets up
4118 firstWindow->assertNoEvents();
4119 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004120 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004121}
4122
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004123/**
4124 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4125 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4126 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4127 * natural to the user.
4128 * In this test, we are sending a pointer to both spy window and first window. We then try to
4129 * transfer touch to the second window. The dispatcher should identify the first window as the
4130 * one that should lose the gesture, and therefore the action should be to move the gesture from
4131 * the first window to the second.
4132 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4133 * the other API, as well.
4134 */
4135TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4136 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4137
4138 // Create a couple of windows + a spy window
4139 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004140 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004141 spyWindow->setTrustedOverlay(true);
4142 spyWindow->setSpy(true);
4143 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004144 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004145 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004146 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004147
4148 // Add the windows to the dispatcher
4149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4150
4151 // Send down to the first window
4152 NotifyMotionArgs downMotionArgs =
4153 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4154 ADISPLAY_ID_DEFAULT);
4155 mDispatcher->notifyMotion(&downMotionArgs);
4156 // Only the first window and spy should get the down event
4157 spyWindow->consumeMotionDown();
4158 firstWindow->consumeMotionDown();
4159
4160 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4161 // if f === 'transferTouch'.
4162 TransferFunction f = GetParam();
4163 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4164 ASSERT_TRUE(success);
4165 // The first window gets cancel and the second gets down
4166 firstWindow->consumeMotionCancel();
4167 secondWindow->consumeMotionDown();
4168
4169 // Send up event to the second window
4170 NotifyMotionArgs upMotionArgs =
4171 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4172 ADISPLAY_ID_DEFAULT);
4173 mDispatcher->notifyMotion(&upMotionArgs);
4174 // The first window gets no events and the second+spy get up
4175 firstWindow->assertNoEvents();
4176 spyWindow->consumeMotionUp();
4177 secondWindow->consumeMotionUp();
4178}
4179
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004180TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004181 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004182
4183 PointF touchPoint = {10, 10};
4184
4185 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004186 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004187 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4188 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004189 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004190 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004191 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4192 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004193 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004194
4195 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197
4198 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004199 NotifyMotionArgs downMotionArgs =
4200 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4201 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004202 mDispatcher->notifyMotion(&downMotionArgs);
4203 // Only the first window should get the down event
4204 firstWindow->consumeMotionDown();
4205 secondWindow->assertNoEvents();
4206
4207 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004208 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004209 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004210 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4212 // Only the first window should get the pointer down event
4213 firstWindow->consumeMotionPointerDown(1);
4214 secondWindow->assertNoEvents();
4215
4216 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004217 TransferFunction f = GetParam();
4218 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4219 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004220 // The first window gets cancel and the second gets down and pointer down
4221 firstWindow->consumeMotionCancel();
4222 secondWindow->consumeMotionDown();
4223 secondWindow->consumeMotionPointerDown(1);
4224
4225 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004226 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004227 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004228 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004229 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4230 // The first window gets nothing and the second gets pointer up
4231 firstWindow->assertNoEvents();
4232 secondWindow->consumeMotionPointerUp(1);
4233
4234 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004235 NotifyMotionArgs upMotionArgs =
4236 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4237 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238 mDispatcher->notifyMotion(&upMotionArgs);
4239 // The first window gets nothing and the second gets up
4240 firstWindow->assertNoEvents();
4241 secondWindow->consumeMotionUp();
4242}
4243
Arthur Hungc539dbb2022-12-08 07:45:36 +00004244TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4246
4247 // Create a couple of windows
4248 sp<FakeWindowHandle> firstWindow =
4249 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4250 ADISPLAY_ID_DEFAULT);
4251 firstWindow->setDupTouchToWallpaper(true);
4252 sp<FakeWindowHandle> secondWindow =
4253 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4254 ADISPLAY_ID_DEFAULT);
4255 secondWindow->setDupTouchToWallpaper(true);
4256
4257 sp<FakeWindowHandle> wallpaper1 =
4258 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4259 wallpaper1->setIsWallpaper(true);
4260
4261 sp<FakeWindowHandle> wallpaper2 =
4262 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4263 wallpaper2->setIsWallpaper(true);
4264 // Add the windows to the dispatcher
4265 mDispatcher->setInputWindows(
4266 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4267
4268 // Send down to the first window
4269 NotifyMotionArgs downMotionArgs =
4270 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4271 ADISPLAY_ID_DEFAULT);
4272 mDispatcher->notifyMotion(&downMotionArgs);
4273
4274 // Only the first window should get the down event
4275 firstWindow->consumeMotionDown();
4276 secondWindow->assertNoEvents();
4277 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4278 wallpaper2->assertNoEvents();
4279
4280 // Transfer touch focus to the second window
4281 TransferFunction f = GetParam();
4282 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4283 ASSERT_TRUE(success);
4284
4285 // The first window gets cancel and the second gets down
4286 firstWindow->consumeMotionCancel();
4287 secondWindow->consumeMotionDown();
4288 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4289 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4290
4291 // Send up event to the second window
4292 NotifyMotionArgs upMotionArgs =
4293 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4294 ADISPLAY_ID_DEFAULT);
4295 mDispatcher->notifyMotion(&upMotionArgs);
4296 // The first window gets no events and the second gets up
4297 firstWindow->assertNoEvents();
4298 secondWindow->consumeMotionUp();
4299 wallpaper1->assertNoEvents();
4300 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4301}
4302
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004303// For the cases of single pointer touch and two pointers non-split touch, the api's
4304// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4305// for the case where there are multiple pointers split across several windows.
4306INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4307 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004308 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4309 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004310 return dispatcher->transferTouch(destChannelToken,
4311 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004312 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004313 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4314 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004315 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004316 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004317 }));
4318
Svet Ganov5d3bc372020-01-26 23:11:07 -08004319TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004320 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004321
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004322 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004323 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4324 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004325 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004326
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004327 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004328 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4329 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004330 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004331
4332 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004334
4335 PointF pointInFirst = {300, 200};
4336 PointF pointInSecond = {300, 600};
4337
4338 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004339 NotifyMotionArgs firstDownMotionArgs =
4340 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4341 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004342 mDispatcher->notifyMotion(&firstDownMotionArgs);
4343 // Only the first window should get the down event
4344 firstWindow->consumeMotionDown();
4345 secondWindow->assertNoEvents();
4346
4347 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004348 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004349 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004350 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004351 mDispatcher->notifyMotion(&secondDownMotionArgs);
4352 // The first window gets a move and the second a down
4353 firstWindow->consumeMotionMove();
4354 secondWindow->consumeMotionDown();
4355
4356 // Transfer touch focus to the second window
4357 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4358 // The first window gets cancel and the new gets pointer down (it already saw down)
4359 firstWindow->consumeMotionCancel();
4360 secondWindow->consumeMotionPointerDown(1);
4361
4362 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004363 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004364 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004365 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004366 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4367 // The first window gets nothing and the second gets pointer up
4368 firstWindow->assertNoEvents();
4369 secondWindow->consumeMotionPointerUp(1);
4370
4371 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004372 NotifyMotionArgs upMotionArgs =
4373 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4374 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004375 mDispatcher->notifyMotion(&upMotionArgs);
4376 // The first window gets nothing and the second gets up
4377 firstWindow->assertNoEvents();
4378 secondWindow->consumeMotionUp();
4379}
4380
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004381// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4382// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4383// touch is not supported, so the touch should continue on those windows and the transferred-to
4384// window should get nothing.
4385TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4386 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4387
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004388 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004389 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4390 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004391 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004392
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004393 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004394 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4395 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004396 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004397
4398 // Add the windows to the dispatcher
4399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4400
4401 PointF pointInFirst = {300, 200};
4402 PointF pointInSecond = {300, 600};
4403
4404 // Send down to the first window
4405 NotifyMotionArgs firstDownMotionArgs =
4406 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4407 ADISPLAY_ID_DEFAULT, {pointInFirst});
4408 mDispatcher->notifyMotion(&firstDownMotionArgs);
4409 // Only the first window should get the down event
4410 firstWindow->consumeMotionDown();
4411 secondWindow->assertNoEvents();
4412
4413 // Send down to the second window
4414 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004415 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004416 {pointInFirst, pointInSecond});
4417 mDispatcher->notifyMotion(&secondDownMotionArgs);
4418 // The first window gets a move and the second a down
4419 firstWindow->consumeMotionMove();
4420 secondWindow->consumeMotionDown();
4421
4422 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004423 const bool transferred =
4424 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004425 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4426 ASSERT_FALSE(transferred);
4427 firstWindow->assertNoEvents();
4428 secondWindow->assertNoEvents();
4429
4430 // The rest of the dispatch should proceed as normal
4431 // Send pointer up to the second window
4432 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004433 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004434 {pointInFirst, pointInSecond});
4435 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4436 // The first window gets MOVE and the second gets pointer up
4437 firstWindow->consumeMotionMove();
4438 secondWindow->consumeMotionUp();
4439
4440 // Send up event to the first window
4441 NotifyMotionArgs upMotionArgs =
4442 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4443 ADISPLAY_ID_DEFAULT);
4444 mDispatcher->notifyMotion(&upMotionArgs);
4445 // The first window gets nothing and the second gets up
4446 firstWindow->consumeMotionUp();
4447 secondWindow->assertNoEvents();
4448}
4449
Arthur Hungabbb9d82021-09-01 14:52:30 +00004450// This case will create two windows and one mirrored window on the default display and mirror
4451// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4452// the windows info of second display before default display.
4453TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4454 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4455 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004456 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004457 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004458 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004459 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004460 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004461
4462 sp<FakeWindowHandle> mirrorWindowInPrimary =
4463 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4464 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004465
4466 sp<FakeWindowHandle> firstWindowInSecondary =
4467 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4468 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004469
4470 sp<FakeWindowHandle> secondWindowInSecondary =
4471 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4472 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004473
4474 // Update window info, let it find window handle of second display first.
4475 mDispatcher->setInputWindows(
4476 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4477 {ADISPLAY_ID_DEFAULT,
4478 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4479
4480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4481 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4482 {50, 50}))
4483 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4484
4485 // Window should receive motion event.
4486 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4487
4488 // Transfer touch focus
4489 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4490 secondWindowInPrimary->getToken()));
4491 // The first window gets cancel.
4492 firstWindowInPrimary->consumeMotionCancel();
4493 secondWindowInPrimary->consumeMotionDown();
4494
4495 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4496 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4497 ADISPLAY_ID_DEFAULT, {150, 50}))
4498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4499 firstWindowInPrimary->assertNoEvents();
4500 secondWindowInPrimary->consumeMotionMove();
4501
4502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4503 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4504 {150, 50}))
4505 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4506 firstWindowInPrimary->assertNoEvents();
4507 secondWindowInPrimary->consumeMotionUp();
4508}
4509
4510// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4511// 'transferTouch' api.
4512TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4514 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004515 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004516 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004517 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004518 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004519 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004520
4521 sp<FakeWindowHandle> mirrorWindowInPrimary =
4522 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4523 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004524
4525 sp<FakeWindowHandle> firstWindowInSecondary =
4526 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4527 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004528
4529 sp<FakeWindowHandle> secondWindowInSecondary =
4530 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4531 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004532
4533 // Update window info, let it find window handle of second display first.
4534 mDispatcher->setInputWindows(
4535 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4536 {ADISPLAY_ID_DEFAULT,
4537 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4538
4539 // Touch on second display.
4540 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4541 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4542 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4543
4544 // Window should receive motion event.
4545 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4546
4547 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004548 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004549
4550 // The first window gets cancel.
4551 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4552 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4553
4554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4555 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4556 SECOND_DISPLAY_ID, {150, 50}))
4557 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4558 firstWindowInPrimary->assertNoEvents();
4559 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4560
4561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4562 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4564 firstWindowInPrimary->assertNoEvents();
4565 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4566}
4567
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004568TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004570 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4571 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004572
Vishnu Nair47074b82020-08-14 11:54:47 -07004573 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004575 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004576
4577 window->consumeFocusEvent(true);
4578
4579 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4580 mDispatcher->notifyKey(&keyArgs);
4581
4582 // Window should receive key down event.
4583 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4584}
4585
4586TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004588 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4589 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004590
Arthur Hung72d8dc32020-03-28 00:48:39 +00004591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004592
4593 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4594 mDispatcher->notifyKey(&keyArgs);
4595 mDispatcher->waitForIdle();
4596
4597 window->assertNoEvents();
4598}
4599
4600// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4601TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004603 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4604 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004605
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004607
4608 // Send key
4609 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4610 mDispatcher->notifyKey(&keyArgs);
4611 // Send motion
4612 NotifyMotionArgs motionArgs =
4613 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4614 ADISPLAY_ID_DEFAULT);
4615 mDispatcher->notifyMotion(&motionArgs);
4616
4617 // Window should receive only the motion event
4618 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4619 window->assertNoEvents(); // Key event or focus event will not be received
4620}
4621
arthurhungea3f4fc2020-12-21 23:18:53 +08004622TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4624
arthurhungea3f4fc2020-12-21 23:18:53 +08004625 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004626 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4627 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004628 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004629
arthurhungea3f4fc2020-12-21 23:18:53 +08004630 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004631 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4632 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004633 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004634
4635 // Add the windows to the dispatcher
4636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4637
4638 PointF pointInFirst = {300, 200};
4639 PointF pointInSecond = {300, 600};
4640
4641 // Send down to the first window
4642 NotifyMotionArgs firstDownMotionArgs =
4643 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4644 ADISPLAY_ID_DEFAULT, {pointInFirst});
4645 mDispatcher->notifyMotion(&firstDownMotionArgs);
4646 // Only the first window should get the down event
4647 firstWindow->consumeMotionDown();
4648 secondWindow->assertNoEvents();
4649
4650 // Send down to the second window
4651 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004652 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004653 {pointInFirst, pointInSecond});
4654 mDispatcher->notifyMotion(&secondDownMotionArgs);
4655 // The first window gets a move and the second a down
4656 firstWindow->consumeMotionMove();
4657 secondWindow->consumeMotionDown();
4658
4659 // Send pointer cancel to the second window
4660 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004661 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004662 {pointInFirst, pointInSecond});
4663 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4664 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4665 // The first window gets move and the second gets cancel.
4666 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4667 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4668
4669 // Send up event.
4670 NotifyMotionArgs upMotionArgs =
4671 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4672 ADISPLAY_ID_DEFAULT);
4673 mDispatcher->notifyMotion(&upMotionArgs);
4674 // The first window gets up and the second gets nothing.
4675 firstWindow->consumeMotionUp();
4676 secondWindow->assertNoEvents();
4677}
4678
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004679TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4681
4682 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004683 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4685 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4686 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4687 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4688
Harry Cutts33476232023-01-30 19:57:29 +00004689 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004690 window->assertNoEvents();
4691 mDispatcher->waitForIdle();
4692}
4693
chaviwd1c23182019-12-20 18:44:56 -08004694class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004695public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004696 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004697 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004698 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004699 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004700 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004701 }
4702
chaviwd1c23182019-12-20 18:44:56 -08004703 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4704
4705 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4706 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4707 expectedDisplayId, expectedFlags);
4708 }
4709
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4711
4712 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4713
chaviwd1c23182019-12-20 18:44:56 -08004714 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4715 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4716 expectedDisplayId, expectedFlags);
4717 }
4718
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004719 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4720 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4721 expectedDisplayId, expectedFlags);
4722 }
4723
chaviwd1c23182019-12-20 18:44:56 -08004724 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4725 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4726 expectedDisplayId, expectedFlags);
4727 }
4728
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004729 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004730 mInputReceiver->consumeMotionEvent(
4731 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4732 WithDisplayId(expectedDisplayId),
4733 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004734 }
4735
Arthur Hungfbfa5722021-11-16 02:45:54 +00004736 void consumeMotionPointerDown(int32_t pointerIdx) {
4737 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4738 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4739 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004740 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004741 }
4742
Evan Rosky84f07f02021-04-16 10:42:42 -07004743 MotionEvent* consumeMotion() {
4744 InputEvent* event = mInputReceiver->consume();
4745 if (!event) {
4746 ADD_FAILURE() << "No event was produced";
4747 return nullptr;
4748 }
4749 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4750 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4751 return nullptr;
4752 }
4753 return static_cast<MotionEvent*>(event);
4754 }
4755
chaviwd1c23182019-12-20 18:44:56 -08004756 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4757
4758private:
4759 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004760};
4761
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004762using InputDispatcherMonitorTest = InputDispatcherTest;
4763
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004764/**
4765 * Two entities that receive touch: A window, and a global monitor.
4766 * The touch goes to the window, and then the window disappears.
4767 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4768 * for the monitor, as well.
4769 * 1. foregroundWindow
4770 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4771 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004772TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004773 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4774 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004775 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004776
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004777 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004778
4779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4782 {100, 200}))
4783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4784
4785 // Both the foreground window and the global monitor should receive the touch down
4786 window->consumeMotionDown();
4787 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4788
4789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4790 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4791 ADISPLAY_ID_DEFAULT, {110, 200}))
4792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4793
4794 window->consumeMotionMove();
4795 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4796
4797 // Now the foreground window goes away
4798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4799 window->consumeMotionCancel();
4800 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4801
4802 // If more events come in, there will be no more foreground window to send them to. This will
4803 // cause a cancel for the monitor, as well.
4804 ASSERT_EQ(InputEventInjectionResult::FAILED,
4805 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4806 ADISPLAY_ID_DEFAULT, {120, 200}))
4807 << "Injection should fail because the window was removed";
4808 window->assertNoEvents();
4809 // Global monitor now gets the cancel
4810 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4811}
4812
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004813TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004815 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4816 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004818
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004819 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004820
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004824 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004825 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004826}
4827
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004828TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4829 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004830
Chris Yea209fde2020-07-22 13:54:51 -07004831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004832 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4833 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004835
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004839 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004840 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004841
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004842 // Pilfer pointers from the monitor.
4843 // This should not do anything and the window should continue to receive events.
4844 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004845
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004847 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4848 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004850
4851 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4852 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004853}
4854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004856 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004857 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4858 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4860 window->setWindowOffset(20, 40);
4861 window->setWindowTransform(0, 1, -1, 0);
4862
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004863 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004864
4865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4866 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4868 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4869 MotionEvent* event = monitor.consumeMotion();
4870 // Even though window has transform, gesture monitor must not.
4871 ASSERT_EQ(ui::Transform(), event->getTransform());
4872}
4873
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004874TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004875 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004876 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004877
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004878 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004879 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004880 << "Injection should fail if there is a monitor, but no touchable window";
4881 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004882}
4883
chaviw81e2bb92019-12-18 15:03:51 -08004884TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004885 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004886 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4887 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004888
Arthur Hung72d8dc32020-03-28 00:48:39 +00004889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004890
4891 NotifyMotionArgs motionArgs =
4892 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4893 ADISPLAY_ID_DEFAULT);
4894
4895 mDispatcher->notifyMotion(&motionArgs);
4896 // Window should receive motion down event.
4897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4898
4899 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004900 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004901 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4902 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4903 motionArgs.pointerCoords[0].getX() - 10);
4904
4905 mDispatcher->notifyMotion(&motionArgs);
4906 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004907 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004908}
4909
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004910/**
4911 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4912 * the device default right away. In the test scenario, we check both the default value,
4913 * and the action of enabling / disabling.
4914 */
4915TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004917 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4918 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004919 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004920
4921 // Set focused application.
4922 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004923 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004924
4925 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004927 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004928 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004929
4930 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004931 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004933 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004934
4935 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004936 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004937 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004938 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004939 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004941 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004942 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004943
4944 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004945 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004947 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004948
4949 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004950 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004951 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004952 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004953 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004955 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004956 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004957
4958 window->assertNoEvents();
4959}
4960
Gang Wange9087892020-01-07 12:17:14 -05004961TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004962 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004963 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4964 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004965
4966 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004967 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004968
Arthur Hung72d8dc32020-03-28 00:48:39 +00004969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004970 setFocusedWindow(window);
4971
Harry Cutts33476232023-01-30 19:57:29 +00004972 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004973
4974 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4975 mDispatcher->notifyKey(&keyArgs);
4976
4977 InputEvent* event = window->consume();
4978 ASSERT_NE(event, nullptr);
4979
4980 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4981 ASSERT_NE(verified, nullptr);
4982 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4983
4984 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4985 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4986 ASSERT_EQ(keyArgs.source, verified->source);
4987 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4988
4989 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4990
4991 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004992 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004993 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004994 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4995 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4996 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4997 ASSERT_EQ(0, verifiedKey.repeatCount);
4998}
4999
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005000TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005001 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005002 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5003 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005004
5005 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5006
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005007 ui::Transform transform;
5008 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5009
5010 gui::DisplayInfo displayInfo;
5011 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
5012 displayInfo.transform = transform;
5013
5014 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005015
5016 NotifyMotionArgs motionArgs =
5017 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5018 ADISPLAY_ID_DEFAULT);
5019 mDispatcher->notifyMotion(&motionArgs);
5020
5021 InputEvent* event = window->consume();
5022 ASSERT_NE(event, nullptr);
5023
5024 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5025 ASSERT_NE(verified, nullptr);
5026 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
5027
5028 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
5029 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
5030 EXPECT_EQ(motionArgs.source, verified->source);
5031 EXPECT_EQ(motionArgs.displayId, verified->displayId);
5032
5033 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
5034
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005035 const vec2 rawXY =
5036 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
5037 motionArgs.pointerCoords[0].getXYValue());
5038 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
5039 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005040 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005041 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005042 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005043 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
5044 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
5045}
5046
chaviw09c8d2d2020-08-24 15:48:26 -07005047/**
5048 * Ensure that separate calls to sign the same data are generating the same key.
5049 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
5050 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
5051 * tests.
5052 */
5053TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
5054 KeyEvent event = getTestKeyEvent();
5055 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5056
5057 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
5058 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
5059 ASSERT_EQ(hmac1, hmac2);
5060}
5061
5062/**
5063 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
5064 */
5065TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
5066 KeyEvent event = getTestKeyEvent();
5067 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5068 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
5069
5070 verifiedEvent.deviceId += 1;
5071 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5072
5073 verifiedEvent.source += 1;
5074 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5075
5076 verifiedEvent.eventTimeNanos += 1;
5077 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5078
5079 verifiedEvent.displayId += 1;
5080 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5081
5082 verifiedEvent.action += 1;
5083 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5084
5085 verifiedEvent.downTimeNanos += 1;
5086 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5087
5088 verifiedEvent.flags += 1;
5089 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5090
5091 verifiedEvent.keyCode += 1;
5092 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5093
5094 verifiedEvent.scanCode += 1;
5095 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5096
5097 verifiedEvent.metaState += 1;
5098 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5099
5100 verifiedEvent.repeatCount += 1;
5101 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5102}
5103
Vishnu Nair958da932020-08-21 17:12:37 -07005104TEST_F(InputDispatcherTest, SetFocusedWindow) {
5105 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5106 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005107 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005108 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005109 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005110 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5111
5112 // Top window is also focusable but is not granted focus.
5113 windowTop->setFocusable(true);
5114 windowSecond->setFocusable(true);
5115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5116 setFocusedWindow(windowSecond);
5117
5118 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5120 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005121
5122 // Focused window should receive event.
5123 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5124 windowTop->assertNoEvents();
5125}
5126
5127TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5128 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5129 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005130 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5132
5133 window->setFocusable(true);
5134 // Release channel for window is no longer valid.
5135 window->releaseChannel();
5136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5137 setFocusedWindow(window);
5138
5139 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5141 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005142
5143 // window channel is invalid, so it should not receive any input event.
5144 window->assertNoEvents();
5145}
5146
5147TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5149 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005150 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005151 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5153
Vishnu Nair958da932020-08-21 17:12:37 -07005154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5155 setFocusedWindow(window);
5156
5157 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005158 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5159 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005160
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005161 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005162 window->assertNoEvents();
5163}
5164
5165TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5166 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5167 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005168 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005169 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005170 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005171 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5172
5173 windowTop->setFocusable(true);
5174 windowSecond->setFocusable(true);
5175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5176 setFocusedWindow(windowTop);
5177 windowTop->consumeFocusEvent(true);
5178
5179 setFocusedWindow(windowSecond, windowTop);
5180 windowSecond->consumeFocusEvent(true);
5181 windowTop->consumeFocusEvent(false);
5182
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5184 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005185
5186 // Focused window should receive event.
5187 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5188}
5189
5190TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5191 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5192 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005193 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005194 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005195 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005196 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5197
5198 windowTop->setFocusable(true);
5199 windowSecond->setFocusable(true);
5200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5201 setFocusedWindow(windowSecond, windowTop);
5202
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005203 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5204 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005205
5206 // Event should be dropped.
5207 windowTop->assertNoEvents();
5208 windowSecond->assertNoEvents();
5209}
5210
5211TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5213 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005214 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005215 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005216 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5217 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005218 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5219
5220 window->setFocusable(true);
5221 previousFocusedWindow->setFocusable(true);
5222 window->setVisible(false);
5223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5224 setFocusedWindow(previousFocusedWindow);
5225 previousFocusedWindow->consumeFocusEvent(true);
5226
5227 // Requesting focus on invisible window takes focus from currently focused window.
5228 setFocusedWindow(window);
5229 previousFocusedWindow->consumeFocusEvent(false);
5230
5231 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005233 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5234 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005235
5236 // Window does not get focus event or key down.
5237 window->assertNoEvents();
5238
5239 // Window becomes visible.
5240 window->setVisible(true);
5241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5242
5243 // Window receives focus event.
5244 window->consumeFocusEvent(true);
5245 // Focused window receives key down.
5246 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5247}
5248
Vishnu Nair599f1412021-06-21 10:39:58 -07005249TEST_F(InputDispatcherTest, DisplayRemoved) {
5250 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5251 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005252 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5254
5255 // window is granted focus.
5256 window->setFocusable(true);
5257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5258 setFocusedWindow(window);
5259 window->consumeFocusEvent(true);
5260
5261 // When a display is removed window loses focus.
5262 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5263 window->consumeFocusEvent(false);
5264}
5265
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005266/**
5267 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5268 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5269 * of the 'slipperyEnterWindow'.
5270 *
5271 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5272 * a way so that the touched location is no longer covered by the top window.
5273 *
5274 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5275 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5276 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5277 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5278 * with ACTION_DOWN).
5279 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5280 * window moved itself away from the touched location and had Flag::SLIPPERY.
5281 *
5282 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5283 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5284 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5285 *
5286 * In this test, we ensure that the event received by the bottom window has
5287 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5288 */
5289TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005290 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5291 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005292
5293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5294 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5295
5296 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005297 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005298 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005299 // Make sure this one overlaps the bottom window
5300 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5301 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5302 // one. Windows with the same owner are not considered to be occluding each other.
5303 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5304
5305 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005306 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005307 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5308
5309 mDispatcher->setInputWindows(
5310 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5311
5312 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5313 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5314 ADISPLAY_ID_DEFAULT, {{50, 50}});
5315 mDispatcher->notifyMotion(&args);
5316 slipperyExitWindow->consumeMotionDown();
5317 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5318 mDispatcher->setInputWindows(
5319 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5320
5321 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5322 ADISPLAY_ID_DEFAULT, {{51, 51}});
5323 mDispatcher->notifyMotion(&args);
5324
5325 slipperyExitWindow->consumeMotionCancel();
5326
5327 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5328 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5329}
5330
Garfield Tan1c7bc862020-01-28 13:24:04 -08005331class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5332protected:
5333 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5334 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5335
Chris Yea209fde2020-07-22 13:54:51 -07005336 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005337 sp<FakeWindowHandle> mWindow;
5338
5339 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005340 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005341 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005342 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005343 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5344 ASSERT_EQ(OK, mDispatcher->start());
5345
5346 setUpWindow();
5347 }
5348
5349 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005350 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005351 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005352
Vishnu Nair47074b82020-08-14 11:54:47 -07005353 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005355 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005356 mWindow->consumeFocusEvent(true);
5357 }
5358
Chris Ye2ad95392020-09-01 13:44:44 -07005359 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005360 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005361 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005362 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5363 mDispatcher->notifyKey(&keyArgs);
5364
5365 // Window should receive key down event.
5366 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5367 }
5368
5369 void expectKeyRepeatOnce(int32_t repeatCount) {
5370 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5371 InputEvent* repeatEvent = mWindow->consume();
5372 ASSERT_NE(nullptr, repeatEvent);
5373
5374 uint32_t eventType = repeatEvent->getType();
5375 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5376
5377 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5378 uint32_t eventAction = repeatKeyEvent->getAction();
5379 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5380 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5381 }
5382
Chris Ye2ad95392020-09-01 13:44:44 -07005383 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005384 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005385 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005386 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5387 mDispatcher->notifyKey(&keyArgs);
5388
5389 // Window should receive key down event.
5390 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005391 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005392 }
5393};
5394
5395TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005396 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005397 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5398 expectKeyRepeatOnce(repeatCount);
5399 }
5400}
5401
5402TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005403 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005404 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5405 expectKeyRepeatOnce(repeatCount);
5406 }
Harry Cutts33476232023-01-30 19:57:29 +00005407 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005408 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005409 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5410 expectKeyRepeatOnce(repeatCount);
5411 }
5412}
5413
5414TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005415 sendAndConsumeKeyDown(/*deviceId=*/1);
5416 expectKeyRepeatOnce(/*repeatCount=*/1);
5417 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005418 mWindow->assertNoEvents();
5419}
5420
5421TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005422 sendAndConsumeKeyDown(/*deviceId=*/1);
5423 expectKeyRepeatOnce(/*repeatCount=*/1);
5424 sendAndConsumeKeyDown(/*deviceId=*/2);
5425 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005426 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005427 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005428 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005429 expectKeyRepeatOnce(/*repeatCount=*/2);
5430 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005431 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005432 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005433 mWindow->assertNoEvents();
5434}
5435
5436TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005437 sendAndConsumeKeyDown(/*deviceId=*/1);
5438 expectKeyRepeatOnce(/*repeatCount=*/1);
5439 sendAndConsumeKeyDown(/*deviceId=*/2);
5440 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005441 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005442 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005443 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005444 mWindow->assertNoEvents();
5445}
5446
liushenxiang42232912021-05-21 20:24:09 +08005447TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5448 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005449 expectKeyRepeatOnce(/*repeatCount=*/1);
5450 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005451 mDispatcher->notifyDeviceReset(&args);
5452 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5453 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5454 mWindow->assertNoEvents();
5455}
5456
Garfield Tan1c7bc862020-01-28 13:24:04 -08005457TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Harry Cutts33476232023-01-30 19:57:29 +00005458 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005459 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5460 InputEvent* repeatEvent = mWindow->consume();
5461 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5462 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5463 IdGenerator::getSource(repeatEvent->getId()));
5464 }
5465}
5466
5467TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Harry Cutts33476232023-01-30 19:57:29 +00005468 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005469
5470 std::unordered_set<int32_t> idSet;
5471 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5472 InputEvent* repeatEvent = mWindow->consume();
5473 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5474 int32_t id = repeatEvent->getId();
5475 EXPECT_EQ(idSet.end(), idSet.find(id));
5476 idSet.insert(id);
5477 }
5478}
5479
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005480/* Test InputDispatcher for MultiDisplay */
5481class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5482public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005483 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005484 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005485
Chris Yea209fde2020-07-22 13:54:51 -07005486 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005487 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005488 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005489
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005490 // Set focus window for primary display, but focused display would be second one.
5491 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005492 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005494 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005495 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005496
Chris Yea209fde2020-07-22 13:54:51 -07005497 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005498 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005499 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005500 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005501 // Set focus display to second one.
5502 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5503 // Set focus window for second display.
5504 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005505 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005506 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005507 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005508 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005509 }
5510
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005511 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005512 InputDispatcherTest::TearDown();
5513
Chris Yea209fde2020-07-22 13:54:51 -07005514 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005515 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005516 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005517 windowInSecondary.clear();
5518 }
5519
5520protected:
Chris Yea209fde2020-07-22 13:54:51 -07005521 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005522 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005523 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005524 sp<FakeWindowHandle> windowInSecondary;
5525};
5526
5527TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5528 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005532 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005533 windowInSecondary->assertNoEvents();
5534
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005535 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5538 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005539 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005540 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005541}
5542
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005543TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005544 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5546 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005547 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005548 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005549 windowInSecondary->assertNoEvents();
5550
5551 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005553 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005554 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005555 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005556
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005557 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005558 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005559
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005560 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005561 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5562 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005563
5564 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005565 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005566 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005567 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005568 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005569 windowInSecondary->assertNoEvents();
5570}
5571
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005572// Test per-display input monitors for motion event.
5573TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005574 FakeMonitorReceiver monitorInPrimary =
5575 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5576 FakeMonitorReceiver monitorInSecondary =
5577 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005578
5579 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5581 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5582 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005583 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005584 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005585 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005586 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005587
5588 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5591 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005592 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005593 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005594 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005595 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005596
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08005597 // Lift up the touch from the second display
5598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5599 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5600 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5601 windowInSecondary->consumeMotionUp(SECOND_DISPLAY_ID);
5602 monitorInSecondary.consumeMotionUp(SECOND_DISPLAY_ID);
5603
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005604 // Test inject a non-pointer motion event.
5605 // If specific a display, it will dispatch to the focused window of particular display,
5606 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5608 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005610 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005611 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005612 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005613 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005614}
5615
5616// Test per-display input monitors for key event.
5617TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005618 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005619 FakeMonitorReceiver monitorInPrimary =
5620 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5621 FakeMonitorReceiver monitorInSecondary =
5622 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005623
5624 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005627 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005628 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005629 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005630 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005631}
5632
Vishnu Nair958da932020-08-21 17:12:37 -07005633TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5634 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005635 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005636 secondWindowInPrimary->setFocusable(true);
5637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5638 setFocusedWindow(secondWindowInPrimary);
5639 windowInPrimary->consumeFocusEvent(false);
5640 secondWindowInPrimary->consumeFocusEvent(true);
5641
5642 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5644 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005645 windowInPrimary->assertNoEvents();
5646 windowInSecondary->assertNoEvents();
5647 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5648}
5649
Arthur Hungdfd528e2021-12-08 13:23:04 +00005650TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5651 FakeMonitorReceiver monitorInPrimary =
5652 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5653 FakeMonitorReceiver monitorInSecondary =
5654 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5655
5656 // Test touch down on primary display.
5657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5660 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5661 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5662
5663 // Test touch down on second display.
5664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5665 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5667 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5668 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5669
5670 // Trigger cancel touch.
5671 mDispatcher->cancelCurrentTouch();
5672 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5673 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5674 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5675 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5676
5677 // Test inject a move motion event, no window/monitor should receive the event.
5678 ASSERT_EQ(InputEventInjectionResult::FAILED,
5679 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5680 ADISPLAY_ID_DEFAULT, {110, 200}))
5681 << "Inject motion event should return InputEventInjectionResult::FAILED";
5682 windowInPrimary->assertNoEvents();
5683 monitorInPrimary.assertNoEvents();
5684
5685 ASSERT_EQ(InputEventInjectionResult::FAILED,
5686 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5687 SECOND_DISPLAY_ID, {110, 200}))
5688 << "Inject motion event should return InputEventInjectionResult::FAILED";
5689 windowInSecondary->assertNoEvents();
5690 monitorInSecondary.assertNoEvents();
5691}
5692
Jackal Guof9696682018-10-05 12:23:23 +08005693class InputFilterTest : public InputDispatcherTest {
5694protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005695 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5696 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005697 NotifyMotionArgs motionArgs;
5698
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005699 motionArgs =
5700 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005701 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005702 motionArgs =
5703 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005704 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005705 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005706 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005707 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5708 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005709 } else {
5710 mFakePolicy->assertFilterInputEventWasNotCalled();
5711 }
5712 }
5713
5714 void testNotifyKey(bool expectToBeFiltered) {
5715 NotifyKeyArgs keyArgs;
5716
5717 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5718 mDispatcher->notifyKey(&keyArgs);
5719 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5720 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005721 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005722
5723 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005724 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005725 } else {
5726 mFakePolicy->assertFilterInputEventWasNotCalled();
5727 }
5728 }
5729};
5730
5731// Test InputFilter for MotionEvent
5732TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5733 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5734 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5735 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5736
5737 // Enable InputFilter
5738 mDispatcher->setInputFilterEnabled(true);
5739 // Test touch on both primary and second display, and check if both events are filtered.
5740 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5741 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5742
5743 // Disable InputFilter
5744 mDispatcher->setInputFilterEnabled(false);
5745 // Test touch on both primary and second display, and check if both events aren't filtered.
5746 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5747 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5748}
5749
5750// Test InputFilter for KeyEvent
5751TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5752 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5753 testNotifyKey(/*expectToBeFiltered*/ false);
5754
5755 // Enable InputFilter
5756 mDispatcher->setInputFilterEnabled(true);
5757 // Send a key event, and check if it is filtered.
5758 testNotifyKey(/*expectToBeFiltered*/ true);
5759
5760 // Disable InputFilter
5761 mDispatcher->setInputFilterEnabled(false);
5762 // Send a key event, and check if it isn't filtered.
5763 testNotifyKey(/*expectToBeFiltered*/ false);
5764}
5765
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005766// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5767// logical display coordinate space.
5768TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5769 ui::Transform firstDisplayTransform;
5770 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5771 ui::Transform secondDisplayTransform;
5772 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5773
5774 std::vector<gui::DisplayInfo> displayInfos(2);
5775 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5776 displayInfos[0].transform = firstDisplayTransform;
5777 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5778 displayInfos[1].transform = secondDisplayTransform;
5779
5780 mDispatcher->onWindowInfosChanged({}, displayInfos);
5781
5782 // Enable InputFilter
5783 mDispatcher->setInputFilterEnabled(true);
5784
5785 // Ensure the correct transforms are used for the displays.
5786 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5787 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5788}
5789
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005790class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5791protected:
5792 virtual void SetUp() override {
5793 InputDispatcherTest::SetUp();
5794
5795 /**
5796 * We don't need to enable input filter to test the injected event policy, but we enabled it
5797 * here to make the tests more realistic, since this policy only matters when inputfilter is
5798 * on.
5799 */
5800 mDispatcher->setInputFilterEnabled(true);
5801
5802 std::shared_ptr<InputApplicationHandle> application =
5803 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005804 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5805 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005806
5807 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5808 mWindow->setFocusable(true);
5809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5810 setFocusedWindow(mWindow);
5811 mWindow->consumeFocusEvent(true);
5812 }
5813
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005814 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5815 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005816 KeyEvent event;
5817
5818 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5819 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5820 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005821 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005822 const int32_t additionalPolicyFlags =
5823 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005825 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005826 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5827 policyFlags | additionalPolicyFlags));
5828
5829 InputEvent* received = mWindow->consume();
5830 ASSERT_NE(nullptr, received);
5831 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005832 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5833 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5834 ASSERT_EQ(flags, keyEvent.getFlags());
5835 }
5836
5837 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5838 int32_t flags) {
5839 MotionEvent event;
5840 PointerProperties pointerProperties[1];
5841 PointerCoords pointerCoords[1];
5842 pointerProperties[0].clear();
5843 pointerProperties[0].id = 0;
5844 pointerCoords[0].clear();
5845 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5846 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5847
5848 ui::Transform identityTransform;
5849 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5850 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5851 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5852 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5853 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005854 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005855 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005856 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5857
5858 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005860 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005861 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5862 policyFlags | additionalPolicyFlags));
5863
5864 InputEvent* received = mWindow->consume();
5865 ASSERT_NE(nullptr, received);
5866 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5867 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5868 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5869 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005870 }
5871
5872private:
5873 sp<FakeWindowHandle> mWindow;
5874};
5875
5876TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005877 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5878 // filter. Without it, the event will no different from a regularly injected event, and the
5879 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005880 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5881 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005882}
5883
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005884TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005885 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005886 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005887 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5888}
5889
5890TEST_F(InputFilterInjectionPolicyTest,
5891 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5892 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005893 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005894 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005895}
5896
5897TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005898 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5899 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005900}
5901
chaviwfd6d3512019-03-25 13:23:49 -07005902class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005903 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005904 InputDispatcherTest::SetUp();
5905
Chris Yea209fde2020-07-22 13:54:51 -07005906 std::shared_ptr<FakeApplicationHandle> application =
5907 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005908 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005909 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005910 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005911
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005912 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005913 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005914 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005915
5916 // Set focused application.
5917 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005918 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005919
5920 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005922 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005923 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005924 }
5925
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005926 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005927 InputDispatcherTest::TearDown();
5928
5929 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005930 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005931 }
5932
5933protected:
5934 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005935 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005936 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005937};
5938
5939// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5940// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5941// the onPointerDownOutsideFocus callback.
5942TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005944 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5945 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005947 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005948
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005949 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005950 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5951}
5952
5953// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5954// DOWN on the window that doesn't have focus. Ensure no window received the
5955// onPointerDownOutsideFocus callback.
5956TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005958 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005959 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005960 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005961
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005962 ASSERT_TRUE(mDispatcher->waitForIdle());
5963 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005964}
5965
5966// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5967// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5968TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5970 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005971 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005972 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005973
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005974 ASSERT_TRUE(mDispatcher->waitForIdle());
5975 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005976}
5977
5978// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5979// DOWN on the window that already has focus. Ensure no window received the
5980// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005981TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005984 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005985 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005986 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005987
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005988 ASSERT_TRUE(mDispatcher->waitForIdle());
5989 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005990}
5991
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005992// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5993// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5994TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5995 const MotionEvent event =
5996 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5997 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005998 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005999 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
6000 .build();
6001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
6002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6003 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
6004
6005 ASSERT_TRUE(mDispatcher->waitForIdle());
6006 mFakePolicy->assertOnPointerDownWasNotCalled();
6007 // Ensure that the unfocused window did not receive any FOCUS events.
6008 mUnfocusedWindow->assertNoEvents();
6009}
6010
chaviwaf87b3e2019-10-01 16:59:28 -07006011// These tests ensures we can send touch events to a single client when there are multiple input
6012// windows that point to the same client token.
6013class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
6014 virtual void SetUp() override {
6015 InputDispatcherTest::SetUp();
6016
Chris Yea209fde2020-07-22 13:54:51 -07006017 std::shared_ptr<FakeApplicationHandle> application =
6018 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006019 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
6020 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07006021 mWindow1->setFrame(Rect(0, 0, 100, 100));
6022
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006023 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
6024 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07006025 mWindow2->setFrame(Rect(100, 100, 200, 200));
6026
Arthur Hung72d8dc32020-03-28 00:48:39 +00006027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07006028 }
6029
6030protected:
6031 sp<FakeWindowHandle> mWindow1;
6032 sp<FakeWindowHandle> mWindow2;
6033
6034 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05006035 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07006036 vec2 vals = windowInfo->transform.transform(point.x, point.y);
6037 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07006038 }
6039
6040 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
6041 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01006042 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07006043 InputEvent* event = window->consume();
6044
6045 ASSERT_NE(nullptr, event) << name.c_str()
6046 << ": consumer should have returned non-NULL event.";
6047
6048 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
6049 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
6050 << " event, got " << inputEventTypeToString(event->getType()) << " event";
6051
6052 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00006053 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08006054 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07006055
6056 for (size_t i = 0; i < points.size(); i++) {
6057 float expectedX = points[i].x;
6058 float expectedY = points[i].y;
6059
6060 EXPECT_EQ(expectedX, motionEvent.getX(i))
6061 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
6062 << ", got " << motionEvent.getX(i);
6063 EXPECT_EQ(expectedY, motionEvent.getY(i))
6064 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
6065 << ", got " << motionEvent.getY(i);
6066 }
6067 }
chaviw9eaa22c2020-07-01 16:21:27 -07006068
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08006069 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07006070 std::vector<PointF> expectedPoints) {
6071 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
6072 ADISPLAY_ID_DEFAULT, touchedPoints);
6073 mDispatcher->notifyMotion(&motionArgs);
6074
6075 // Always consume from window1 since it's the window that has the InputReceiver
6076 consumeMotionEvent(mWindow1, action, expectedPoints);
6077 }
chaviwaf87b3e2019-10-01 16:59:28 -07006078};
6079
6080TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
6081 // Touch Window 1
6082 PointF touchedPoint = {10, 10};
6083 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006084 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006085
6086 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006087 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006088
6089 // Touch Window 2
6090 touchedPoint = {150, 150};
6091 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006092 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006093}
6094
chaviw9eaa22c2020-07-01 16:21:27 -07006095TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
6096 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07006097 mWindow2->setWindowScale(0.5f, 0.5f);
6098
6099 // Touch Window 1
6100 PointF touchedPoint = {10, 10};
6101 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006102 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006103 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006104 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006105
6106 // Touch Window 2
6107 touchedPoint = {150, 150};
6108 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006109 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
6110 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006111
chaviw9eaa22c2020-07-01 16:21:27 -07006112 // Update the transform so rotation is set
6113 mWindow2->setWindowTransform(0, -1, 1, 0);
6114 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
6115 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006116}
6117
chaviw9eaa22c2020-07-01 16:21:27 -07006118TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006119 mWindow2->setWindowScale(0.5f, 0.5f);
6120
6121 // Touch Window 1
6122 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6123 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006124 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006125
6126 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006127 touchedPoints.push_back(PointF{150, 150});
6128 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006129 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006130
chaviw9eaa22c2020-07-01 16:21:27 -07006131 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006132 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006133 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006134
chaviw9eaa22c2020-07-01 16:21:27 -07006135 // Update the transform so rotation is set for Window 2
6136 mWindow2->setWindowTransform(0, -1, 1, 0);
6137 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006138 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006139}
6140
chaviw9eaa22c2020-07-01 16:21:27 -07006141TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006142 mWindow2->setWindowScale(0.5f, 0.5f);
6143
6144 // Touch Window 1
6145 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6146 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006147 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006148
6149 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006150 touchedPoints.push_back(PointF{150, 150});
6151 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006152
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006153 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006154
6155 // Move both windows
6156 touchedPoints = {{20, 20}, {175, 175}};
6157 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6158 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6159
chaviw9eaa22c2020-07-01 16:21:27 -07006160 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006161
chaviw9eaa22c2020-07-01 16:21:27 -07006162 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006163 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006164 expectedPoints.pop_back();
6165
6166 // Touch Window 2
6167 mWindow2->setWindowTransform(0, -1, 1, 0);
6168 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006169 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006170
6171 // Move both windows
6172 touchedPoints = {{20, 20}, {175, 175}};
6173 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6174 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6175
6176 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006177}
6178
6179TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6180 mWindow1->setWindowScale(0.5f, 0.5f);
6181
6182 // Touch Window 1
6183 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6184 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006185 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006186
6187 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006188 touchedPoints.push_back(PointF{150, 150});
6189 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006190
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006191 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006192
6193 // Move both windows
6194 touchedPoints = {{20, 20}, {175, 175}};
6195 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6196 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6197
chaviw9eaa22c2020-07-01 16:21:27 -07006198 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006199}
6200
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006201class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6202 virtual void SetUp() override {
6203 InputDispatcherTest::SetUp();
6204
Chris Yea209fde2020-07-22 13:54:51 -07006205 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006206 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006207 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6208 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006209 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006210 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006211 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006212
6213 // Set focused application.
6214 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6215
6216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006217 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006218 mWindow->consumeFocusEvent(true);
6219 }
6220
6221 virtual void TearDown() override {
6222 InputDispatcherTest::TearDown();
6223 mWindow.clear();
6224 }
6225
6226protected:
Chris Yea209fde2020-07-22 13:54:51 -07006227 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006228 sp<FakeWindowHandle> mWindow;
6229 static constexpr PointF WINDOW_LOCATION = {20, 20};
6230
6231 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006233 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6234 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006236 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6237 WINDOW_LOCATION));
6238 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006239
6240 sp<FakeWindowHandle> addSpyWindow() {
6241 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006242 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006243 spy->setTrustedOverlay(true);
6244 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006245 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006246 spy->setDispatchingTimeout(30ms);
6247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6248 return spy;
6249 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006250};
6251
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006252// Send a tap and respond, which should not cause an ANR.
6253TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6254 tapOnWindow();
6255 mWindow->consumeMotionDown();
6256 mWindow->consumeMotionUp();
6257 ASSERT_TRUE(mDispatcher->waitForIdle());
6258 mFakePolicy->assertNotifyAnrWasNotCalled();
6259}
6260
6261// Send a regular key and respond, which should not cause an ANR.
6262TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006264 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6265 ASSERT_TRUE(mDispatcher->waitForIdle());
6266 mFakePolicy->assertNotifyAnrWasNotCalled();
6267}
6268
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006269TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6270 mWindow->setFocusable(false);
6271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6272 mWindow->consumeFocusEvent(false);
6273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006274 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006275 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6276 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6277 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006279 // Key will not go to window because we have no focused window.
6280 // The 'no focused window' ANR timer should start instead.
6281
6282 // Now, the focused application goes away.
6283 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6284 // The key should get dropped and there should be no ANR.
6285
6286 ASSERT_TRUE(mDispatcher->waitForIdle());
6287 mFakePolicy->assertNotifyAnrWasNotCalled();
6288}
6289
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006290// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006291// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6292// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006293TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006295 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6296 WINDOW_LOCATION));
6297
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006298 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6299 ASSERT_TRUE(sequenceNum);
6300 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006301 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006304 mWindow->consumeMotionEvent(
6305 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006306 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006307 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006308}
6309
6310// Send a key to the app and have the app not respond right away.
6311TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6312 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006314 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6315 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006316 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006317 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006318 ASSERT_TRUE(mDispatcher->waitForIdle());
6319}
6320
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006321// We have a focused application, but no focused window
6322TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006323 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006324 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6325 mWindow->consumeFocusEvent(false);
6326
6327 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006329 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6330 WINDOW_LOCATION));
6331 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6332 mDispatcher->waitForIdle();
6333 mFakePolicy->assertNotifyAnrWasNotCalled();
6334
6335 // Once a focused event arrives, we get an ANR for this application
6336 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6337 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006338 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006339 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6340 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006341 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006342 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006343 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006344 ASSERT_TRUE(mDispatcher->waitForIdle());
6345}
6346
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006347/**
6348 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6349 * there will not be an ANR.
6350 */
6351TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6352 mWindow->setFocusable(false);
6353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6354 mWindow->consumeFocusEvent(false);
6355
6356 KeyEvent event;
6357 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6358 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6359
6360 // Define a valid key down event that is stale (too old).
6361 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6362 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006363 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006364
6365 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6366
6367 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006368 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006369 InputEventInjectionSync::WAIT_FOR_RESULT,
6370 INJECT_EVENT_TIMEOUT, policyFlags);
6371 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6372 << "Injection should fail because the event is stale";
6373
6374 ASSERT_TRUE(mDispatcher->waitForIdle());
6375 mFakePolicy->assertNotifyAnrWasNotCalled();
6376 mWindow->assertNoEvents();
6377}
6378
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006379// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006380// Make sure that we don't notify policy twice about the same ANR.
6381TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006382 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6384 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006385
6386 // Once a focused event arrives, we get an ANR for this application
6387 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6388 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006389 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006390 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6391 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006392 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006393 const std::chrono::duration appTimeout =
6394 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6395 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006396
Vishnu Naire4df8752022-09-08 09:17:55 -07006397 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006398 // ANR should not be raised again. It is up to policy to do that if it desires.
6399 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006400
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006401 // If we now get a focused window, the ANR should stop, but the policy handles that via
6402 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006403 ASSERT_TRUE(mDispatcher->waitForIdle());
6404}
6405
6406// We have a focused application, but no focused window
6407TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006408 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6410 mWindow->consumeFocusEvent(false);
6411
6412 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006413 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006414 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006415 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6416 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006417
Vishnu Naire4df8752022-09-08 09:17:55 -07006418 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6419 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006420
6421 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006422 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006423 ASSERT_TRUE(mDispatcher->waitForIdle());
6424 mWindow->assertNoEvents();
6425}
6426
6427/**
6428 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6429 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6430 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6431 * the ANR mechanism should still work.
6432 *
6433 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6434 * DOWN event, while not responding on the second one.
6435 */
6436TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6437 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6438 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6439 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6440 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6441 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006442 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006443
6444 // Now send ACTION_UP, with identical timestamp
6445 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6446 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6447 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6448 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006449 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006450
6451 // We have now sent down and up. Let's consume first event and then ANR on the second.
6452 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6453 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006454 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006455}
6456
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006457// A spy window can receive an ANR
6458TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6459 sp<FakeWindowHandle> spy = addSpyWindow();
6460
6461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6463 WINDOW_LOCATION));
6464 mWindow->consumeMotionDown();
6465
6466 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6467 ASSERT_TRUE(sequenceNum);
6468 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006469 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006470
6471 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006472 spy->consumeMotionEvent(
6473 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006474 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006475 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006476}
6477
6478// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006479// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006480TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6481 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006482
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6484 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006485 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006487
6488 // Stuck on the ACTION_UP
6489 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006490 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006491
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006492 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006493 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006494 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6495 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006496
6497 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6498 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006499 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006500 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006501 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006502}
6503
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006504// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006505// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006506TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6507 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006508
6509 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006510 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6511 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006512
6513 mWindow->consumeMotionDown();
6514 // Stuck on the ACTION_UP
6515 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006516 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006517
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006518 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006519 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006520 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6521 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006522
6523 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6524 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006525 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006526 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006527 spy->assertNoEvents();
6528}
6529
6530TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6531 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6532
6533 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6534
6535 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6536 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6537 WINDOW_LOCATION));
6538
6539 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6540 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6541 ASSERT_TRUE(consumeSeq);
6542
Prabir Pradhanedd96402022-02-15 01:46:16 -08006543 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006544
6545 monitor.finishEvent(*consumeSeq);
6546 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6547
6548 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006549 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006550}
6551
6552// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6553// process events, you don't get an anr. When the window later becomes unresponsive again, you
6554// get an ANR again.
6555// 1. tap -> block on ACTION_UP -> receive ANR
6556// 2. consume all pending events (= queue becomes healthy again)
6557// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6558TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6559 tapOnWindow();
6560
6561 mWindow->consumeMotionDown();
6562 // Block on ACTION_UP
6563 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006564 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006565 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6566 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006567 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006568 mWindow->assertNoEvents();
6569
6570 tapOnWindow();
6571 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006572 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006573 mWindow->consumeMotionUp();
6574
6575 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006576 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006577 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006578 mWindow->assertNoEvents();
6579}
6580
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006581// If a connection remains unresponsive for a while, make sure policy is only notified once about
6582// it.
6583TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006585 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6586 WINDOW_LOCATION));
6587
6588 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006589 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006590 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006591 // 'notifyConnectionUnresponsive' should only be called once per connection
6592 mFakePolicy->assertNotifyAnrWasNotCalled();
6593 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006594 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006595 mWindow->consumeMotionEvent(
6596 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006597 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006598 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006599 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006600 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006601}
6602
6603/**
6604 * If a window is processing a motion event, and then a key event comes in, the key event should
6605 * not to to the focused window until the motion is processed.
6606 *
6607 * Warning!!!
6608 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6609 * and the injection timeout that we specify when injecting the key.
6610 * We must have the injection timeout (10ms) be smaller than
6611 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6612 *
6613 * If that value changes, this test should also change.
6614 */
6615TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6616 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6618
6619 tapOnWindow();
6620 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6621 ASSERT_TRUE(downSequenceNum);
6622 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6623 ASSERT_TRUE(upSequenceNum);
6624 // Don't finish the events yet, and send a key
6625 // Injection will "succeed" because we will eventually give up and send the key to the focused
6626 // window even if motions are still being processed. But because the injection timeout is short,
6627 // we will receive INJECTION_TIMED_OUT as the result.
6628
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006629 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006630 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006631 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6632 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006633 // Key will not be sent to the window, yet, because the window is still processing events
6634 // and the key remains pending, waiting for the touch events to be processed
6635 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6636 ASSERT_FALSE(keySequenceNum);
6637
6638 std::this_thread::sleep_for(500ms);
6639 // if we wait long enough though, dispatcher will give up, and still send the key
6640 // to the focused window, even though we have not yet finished the motion event
6641 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6642 mWindow->finishEvent(*downSequenceNum);
6643 mWindow->finishEvent(*upSequenceNum);
6644}
6645
6646/**
6647 * If a window is processing a motion event, and then a key event comes in, the key event should
6648 * not go to the focused window until the motion is processed.
6649 * If then a new motion comes in, then the pending key event should be going to the currently
6650 * focused window right away.
6651 */
6652TEST_F(InputDispatcherSingleWindowAnr,
6653 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6654 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6656
6657 tapOnWindow();
6658 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6659 ASSERT_TRUE(downSequenceNum);
6660 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6661 ASSERT_TRUE(upSequenceNum);
6662 // Don't finish the events yet, and send a key
6663 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006665 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6666 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006667 // At this point, key is still pending, and should not be sent to the application yet.
6668 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6669 ASSERT_FALSE(keySequenceNum);
6670
6671 // Now tap down again. It should cause the pending key to go to the focused window right away.
6672 tapOnWindow();
6673 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6674 // the other events yet. We can finish events in any order.
6675 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6676 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6677 mWindow->consumeMotionDown();
6678 mWindow->consumeMotionUp();
6679 mWindow->assertNoEvents();
6680}
6681
6682class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6683 virtual void SetUp() override {
6684 InputDispatcherTest::SetUp();
6685
Chris Yea209fde2020-07-22 13:54:51 -07006686 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006687 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006688 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6689 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006690 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006691 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006692 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006693
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006694 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6695 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006696 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006697 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006698
6699 // Set focused application.
6700 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006701 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006702
6703 // Expect one focus window exist in display.
6704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006705 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006706 mFocusedWindow->consumeFocusEvent(true);
6707 }
6708
6709 virtual void TearDown() override {
6710 InputDispatcherTest::TearDown();
6711
6712 mUnfocusedWindow.clear();
6713 mFocusedWindow.clear();
6714 }
6715
6716protected:
Chris Yea209fde2020-07-22 13:54:51 -07006717 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006718 sp<FakeWindowHandle> mUnfocusedWindow;
6719 sp<FakeWindowHandle> mFocusedWindow;
6720 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6721 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6722 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6723
6724 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6725
6726 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6727
6728private:
6729 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006731 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6732 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006734 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6735 location));
6736 }
6737};
6738
6739// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6740// should be ANR'd first.
6741TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006743 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6744 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006746 mFocusedWindow->consumeMotionDown();
6747 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006748 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006749 // We consumed all events, so no ANR
6750 ASSERT_TRUE(mDispatcher->waitForIdle());
6751 mFakePolicy->assertNotifyAnrWasNotCalled();
6752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6755 FOCUSED_WINDOW_LOCATION));
6756 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6757 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006758
6759 const std::chrono::duration timeout =
6760 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006761 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006762 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6763 // sequence to make it consistent
6764 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006765 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006766 mFocusedWindow->consumeMotionDown();
6767 // This cancel is generated because the connection was unresponsive
6768 mFocusedWindow->consumeMotionCancel();
6769 mFocusedWindow->assertNoEvents();
6770 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006771 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006772 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6773 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006774 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006775}
6776
6777// If we have 2 windows with identical timeouts that are both unresponsive,
6778// it doesn't matter which order they should have ANR.
6779// But we should receive ANR for both.
6780TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6781 // Set the timeout for unfocused window to match the focused window
6782 mUnfocusedWindow->setDispatchingTimeout(10ms);
6783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6784
6785 tapOnFocusedWindow();
6786 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006787 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6788 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6789 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006790
6791 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006792 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6793 mFocusedWindow->getToken() == anrConnectionToken2);
6794 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6795 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006796
6797 ASSERT_TRUE(mDispatcher->waitForIdle());
6798 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006799
6800 mFocusedWindow->consumeMotionDown();
6801 mFocusedWindow->consumeMotionUp();
6802 mUnfocusedWindow->consumeMotionOutside();
6803
Prabir Pradhanedd96402022-02-15 01:46:16 -08006804 sp<IBinder> responsiveToken1, responsiveToken2;
6805 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6806 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006807
6808 // Both applications should be marked as responsive, in any order
6809 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6810 mFocusedWindow->getToken() == responsiveToken2);
6811 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6812 mUnfocusedWindow->getToken() == responsiveToken2);
6813 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006814}
6815
6816// If a window is already not responding, the second tap on the same window should be ignored.
6817// We should also log an error to account for the dropped event (not tested here).
6818// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6819TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6820 tapOnFocusedWindow();
6821 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006822 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006823 // Receive the events, but don't respond
6824 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6825 ASSERT_TRUE(downEventSequenceNum);
6826 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6827 ASSERT_TRUE(upEventSequenceNum);
6828 const std::chrono::duration timeout =
6829 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006830 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006831
6832 // Tap once again
6833 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006834 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006835 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6836 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006837 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006838 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6839 FOCUSED_WINDOW_LOCATION));
6840 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6841 // valid touch target
6842 mUnfocusedWindow->assertNoEvents();
6843
6844 // Consume the first tap
6845 mFocusedWindow->finishEvent(*downEventSequenceNum);
6846 mFocusedWindow->finishEvent(*upEventSequenceNum);
6847 ASSERT_TRUE(mDispatcher->waitForIdle());
6848 // The second tap did not go to the focused window
6849 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006850 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006851 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6852 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006853 mFakePolicy->assertNotifyAnrWasNotCalled();
6854}
6855
6856// If you tap outside of all windows, there will not be ANR
6857TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006858 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006859 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6860 LOCATION_OUTSIDE_ALL_WINDOWS));
6861 ASSERT_TRUE(mDispatcher->waitForIdle());
6862 mFakePolicy->assertNotifyAnrWasNotCalled();
6863}
6864
6865// Since the focused window is paused, tapping on it should not produce any events
6866TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6867 mFocusedWindow->setPaused(true);
6868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6869
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006870 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006871 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6872 FOCUSED_WINDOW_LOCATION));
6873
6874 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6875 ASSERT_TRUE(mDispatcher->waitForIdle());
6876 // Should not ANR because the window is paused, and touches shouldn't go to it
6877 mFakePolicy->assertNotifyAnrWasNotCalled();
6878
6879 mFocusedWindow->assertNoEvents();
6880 mUnfocusedWindow->assertNoEvents();
6881}
6882
6883/**
6884 * If a window is processing a motion event, and then a key event comes in, the key event should
6885 * not to to the focused window until the motion is processed.
6886 * If a different window becomes focused at this time, the key should go to that window instead.
6887 *
6888 * Warning!!!
6889 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6890 * and the injection timeout that we specify when injecting the key.
6891 * We must have the injection timeout (10ms) be smaller than
6892 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6893 *
6894 * If that value changes, this test should also change.
6895 */
6896TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6897 // Set a long ANR timeout to prevent it from triggering
6898 mFocusedWindow->setDispatchingTimeout(2s);
6899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6900
6901 tapOnUnfocusedWindow();
6902 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6903 ASSERT_TRUE(downSequenceNum);
6904 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6905 ASSERT_TRUE(upSequenceNum);
6906 // Don't finish the events yet, and send a key
6907 // Injection will succeed because we will eventually give up and send the key to the focused
6908 // window even if motions are still being processed.
6909
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006910 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006911 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6912 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006914 // Key will not be sent to the window, yet, because the window is still processing events
6915 // and the key remains pending, waiting for the touch events to be processed
6916 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6917 ASSERT_FALSE(keySequenceNum);
6918
6919 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006920 mFocusedWindow->setFocusable(false);
6921 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006923 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006924
6925 // Focus events should precede the key events
6926 mUnfocusedWindow->consumeFocusEvent(true);
6927 mFocusedWindow->consumeFocusEvent(false);
6928
6929 // Finish the tap events, which should unblock dispatcher
6930 mUnfocusedWindow->finishEvent(*downSequenceNum);
6931 mUnfocusedWindow->finishEvent(*upSequenceNum);
6932
6933 // Now that all queues are cleared and no backlog in the connections, the key event
6934 // can finally go to the newly focused "mUnfocusedWindow".
6935 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6936 mFocusedWindow->assertNoEvents();
6937 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006938 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006939}
6940
6941// When the touch stream is split across 2 windows, and one of them does not respond,
6942// then ANR should be raised and the touch should be canceled for the unresponsive window.
6943// The other window should not be affected by that.
6944TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6945 // Touch Window 1
6946 NotifyMotionArgs motionArgs =
6947 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6948 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6949 mDispatcher->notifyMotion(&motionArgs);
6950 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006951 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006952
6953 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006954 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6955 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006956 mDispatcher->notifyMotion(&motionArgs);
6957
6958 const std::chrono::duration timeout =
6959 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006960 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006961
6962 mUnfocusedWindow->consumeMotionDown();
6963 mFocusedWindow->consumeMotionDown();
6964 // Focused window may or may not receive ACTION_MOVE
6965 // But it should definitely receive ACTION_CANCEL due to the ANR
6966 InputEvent* event;
6967 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6968 ASSERT_TRUE(moveOrCancelSequenceNum);
6969 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6970 ASSERT_NE(nullptr, event);
6971 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6972 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6973 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6974 mFocusedWindow->consumeMotionCancel();
6975 } else {
6976 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6977 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006978 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006979 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6980 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006981
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006982 mUnfocusedWindow->assertNoEvents();
6983 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006984 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006985}
6986
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006987/**
6988 * If we have no focused window, and a key comes in, we start the ANR timer.
6989 * The focused application should add a focused window before the timer runs out to prevent ANR.
6990 *
6991 * If the user touches another application during this time, the key should be dropped.
6992 * Next, if a new focused window comes in, without toggling the focused application,
6993 * then no ANR should occur.
6994 *
6995 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6996 * but in some cases the policy may not update the focused application.
6997 */
6998TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6999 std::shared_ptr<FakeApplicationHandle> focusedApplication =
7000 std::make_shared<FakeApplicationHandle>();
7001 focusedApplication->setDispatchingTimeout(60ms);
7002 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
7003 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
7004 mFocusedWindow->setFocusable(false);
7005
7006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7007 mFocusedWindow->consumeFocusEvent(false);
7008
7009 // Send a key. The ANR timer should start because there is no focused window.
7010 // 'focusedApplication' will get blamed if this timer completes.
7011 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007012 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00007013 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7014 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
7015 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007017
7018 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
7019 // then the injected touches won't cause the focused event to get dropped.
7020 // The dispatcher only checks for whether the queue should be pruned upon queueing.
7021 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
7022 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
7023 // For this test, it means that the key would get delivered to the window once it becomes
7024 // focused.
7025 std::this_thread::sleep_for(10ms);
7026
7027 // Touch unfocused window. This should force the pending key to get dropped.
7028 NotifyMotionArgs motionArgs =
7029 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7030 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
7031 mDispatcher->notifyMotion(&motionArgs);
7032
7033 // We do not consume the motion right away, because that would require dispatcher to first
7034 // process (== drop) the key event, and by that time, ANR will be raised.
7035 // Set the focused window first.
7036 mFocusedWindow->setFocusable(true);
7037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7038 setFocusedWindow(mFocusedWindow);
7039 mFocusedWindow->consumeFocusEvent(true);
7040 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
7041 // to another application. This could be a bug / behaviour in the policy.
7042
7043 mUnfocusedWindow->consumeMotionDown();
7044
7045 ASSERT_TRUE(mDispatcher->waitForIdle());
7046 // Should not ANR because we actually have a focused window. It was just added too slowly.
7047 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
7048}
7049
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007050// These tests ensure we cannot send touch events to a window that's positioned behind a window
7051// that has feature NO_INPUT_CHANNEL.
7052// Layout:
7053// Top (closest to user)
7054// mNoInputWindow (above all windows)
7055// mBottomWindow
7056// Bottom (furthest from user)
7057class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
7058 virtual void SetUp() override {
7059 InputDispatcherTest::SetUp();
7060
7061 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007062 mNoInputWindow =
7063 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7064 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00007065 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007066 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007067 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7068 // It's perfectly valid for this window to not have an associated input channel
7069
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007070 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
7071 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007072 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
7073
7074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7075 }
7076
7077protected:
7078 std::shared_ptr<FakeApplicationHandle> mApplication;
7079 sp<FakeWindowHandle> mNoInputWindow;
7080 sp<FakeWindowHandle> mBottomWindow;
7081};
7082
7083TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
7084 PointF touchedPoint = {10, 10};
7085
7086 NotifyMotionArgs motionArgs =
7087 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7088 ADISPLAY_ID_DEFAULT, {touchedPoint});
7089 mDispatcher->notifyMotion(&motionArgs);
7090
7091 mNoInputWindow->assertNoEvents();
7092 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
7093 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
7094 // and therefore should prevent mBottomWindow from receiving touches
7095 mBottomWindow->assertNoEvents();
7096}
7097
7098/**
7099 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
7100 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
7101 */
7102TEST_F(InputDispatcherMultiWindowOcclusionTests,
7103 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007104 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7105 "Window with input channel and NO_INPUT_CHANNEL",
7106 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007107
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007108 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007109 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7111
7112 PointF touchedPoint = {10, 10};
7113
7114 NotifyMotionArgs motionArgs =
7115 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7116 ADISPLAY_ID_DEFAULT, {touchedPoint});
7117 mDispatcher->notifyMotion(&motionArgs);
7118
7119 mNoInputWindow->assertNoEvents();
7120 mBottomWindow->assertNoEvents();
7121}
7122
Vishnu Nair958da932020-08-21 17:12:37 -07007123class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7124protected:
7125 std::shared_ptr<FakeApplicationHandle> mApp;
7126 sp<FakeWindowHandle> mWindow;
7127 sp<FakeWindowHandle> mMirror;
7128
7129 virtual void SetUp() override {
7130 InputDispatcherTest::SetUp();
7131 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007132 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7133 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7134 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007135 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7136 mWindow->setFocusable(true);
7137 mMirror->setFocusable(true);
7138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7139 }
7140};
7141
7142TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7143 // Request focus on a mirrored window
7144 setFocusedWindow(mMirror);
7145
7146 // window gets focused
7147 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7149 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007150 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
7151}
7152
7153// A focused & mirrored window remains focused only if the window and its mirror are both
7154// focusable.
7155TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7156 setFocusedWindow(mMirror);
7157
7158 // window gets focused
7159 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7161 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007162 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7164 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007165 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7166
7167 mMirror->setFocusable(false);
7168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7169
7170 // window loses focus since one of the windows associated with the token in not focusable
7171 mWindow->consumeFocusEvent(false);
7172
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007173 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7174 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007175 mWindow->assertNoEvents();
7176}
7177
7178// A focused & mirrored window remains focused until the window and its mirror both become
7179// invisible.
7180TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7181 setFocusedWindow(mMirror);
7182
7183 // window gets focused
7184 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7186 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007187 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7189 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007190 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7191
7192 mMirror->setVisible(false);
7193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7194
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7196 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007197 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7199 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007200 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7201
7202 mWindow->setVisible(false);
7203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7204
7205 // window loses focus only after all windows associated with the token become invisible.
7206 mWindow->consumeFocusEvent(false);
7207
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007208 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7209 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007210 mWindow->assertNoEvents();
7211}
7212
7213// A focused & mirrored window remains focused until both windows are removed.
7214TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7215 setFocusedWindow(mMirror);
7216
7217 // window gets focused
7218 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7220 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007221 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7223 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007224 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7225
7226 // single window is removed but the window token remains focused
7227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7228
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7230 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007231 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7233 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007234 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7235
7236 // Both windows are removed
7237 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7238 mWindow->consumeFocusEvent(false);
7239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007240 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7241 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007242 mWindow->assertNoEvents();
7243}
7244
7245// Focus request can be pending until one window becomes visible.
7246TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7247 // Request focus on an invisible mirror.
7248 mWindow->setVisible(false);
7249 mMirror->setVisible(false);
7250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7251 setFocusedWindow(mMirror);
7252
7253 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007255 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7256 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007257
7258 mMirror->setVisible(true);
7259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7260
7261 // window gets focused
7262 mWindow->consumeFocusEvent(true);
7263 // window gets the pending key event
7264 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7265}
Prabir Pradhan99987712020-11-10 18:43:05 -08007266
7267class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7268protected:
7269 std::shared_ptr<FakeApplicationHandle> mApp;
7270 sp<FakeWindowHandle> mWindow;
7271 sp<FakeWindowHandle> mSecondWindow;
7272
7273 void SetUp() override {
7274 InputDispatcherTest::SetUp();
7275 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007276 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007277 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007278 mSecondWindow =
7279 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007280 mSecondWindow->setFocusable(true);
7281
7282 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7284
7285 setFocusedWindow(mWindow);
7286 mWindow->consumeFocusEvent(true);
7287 }
7288
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007289 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7290 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007291 mDispatcher->notifyPointerCaptureChanged(&args);
7292 }
7293
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007294 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7295 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007296 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007297 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7298 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007299 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007300 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007301 }
7302};
7303
7304TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7305 // Ensure that capture cannot be obtained for unfocused windows.
7306 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7307 mFakePolicy->assertSetPointerCaptureNotCalled();
7308 mSecondWindow->assertNoEvents();
7309
7310 // Ensure that capture can be enabled from the focus window.
7311 requestAndVerifyPointerCapture(mWindow, true);
7312
7313 // Ensure that capture cannot be disabled from a window that does not have capture.
7314 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7315 mFakePolicy->assertSetPointerCaptureNotCalled();
7316
7317 // Ensure that capture can be disabled from the window with capture.
7318 requestAndVerifyPointerCapture(mWindow, false);
7319}
7320
7321TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007322 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007323
7324 setFocusedWindow(mSecondWindow);
7325
7326 // Ensure that the capture disabled event was sent first.
7327 mWindow->consumeCaptureEvent(false);
7328 mWindow->consumeFocusEvent(false);
7329 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007330 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007331
7332 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007333 notifyPointerCaptureChanged({});
7334 notifyPointerCaptureChanged(request);
7335 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007336 mWindow->assertNoEvents();
7337 mSecondWindow->assertNoEvents();
7338 mFakePolicy->assertSetPointerCaptureNotCalled();
7339}
7340
7341TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007342 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007343
7344 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007345 notifyPointerCaptureChanged({});
7346 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007347
7348 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007349 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007350 mWindow->consumeCaptureEvent(false);
7351 mWindow->assertNoEvents();
7352}
7353
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007354TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7355 requestAndVerifyPointerCapture(mWindow, true);
7356
7357 // The first window loses focus.
7358 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007359 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007360 mWindow->consumeCaptureEvent(false);
7361
7362 // Request Pointer Capture from the second window before the notification from InputReader
7363 // arrives.
7364 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007365 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007366
7367 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007368 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007369
7370 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007371 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007372
7373 mSecondWindow->consumeFocusEvent(true);
7374 mSecondWindow->consumeCaptureEvent(true);
7375}
7376
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007377TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7378 // App repeatedly enables and disables capture.
7379 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7380 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7381 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7382 mFakePolicy->assertSetPointerCaptureCalled(false);
7383 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7384 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7385
7386 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7387 // first request is now stale, this should do nothing.
7388 notifyPointerCaptureChanged(firstRequest);
7389 mWindow->assertNoEvents();
7390
7391 // InputReader notifies that the second request was enabled.
7392 notifyPointerCaptureChanged(secondRequest);
7393 mWindow->consumeCaptureEvent(true);
7394}
7395
Prabir Pradhan7092e262022-05-03 16:51:09 +00007396TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7397 requestAndVerifyPointerCapture(mWindow, true);
7398
7399 // App toggles pointer capture off and on.
7400 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7401 mFakePolicy->assertSetPointerCaptureCalled(false);
7402
7403 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7404 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7405
7406 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7407 // preceding "disable" request.
7408 notifyPointerCaptureChanged(enableRequest);
7409
7410 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7411 // any notifications.
7412 mWindow->assertNoEvents();
7413}
7414
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007415class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7416protected:
7417 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007418
7419 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7420 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7421
7422 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7423 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7424
7425 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7426 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7427 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7428 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7429 MAXIMUM_OBSCURING_OPACITY);
7430
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007431 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007432 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007433 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007434
7435 sp<FakeWindowHandle> mTouchWindow;
7436
7437 virtual void SetUp() override {
7438 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007439 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007440 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7441 }
7442
7443 virtual void TearDown() override {
7444 InputDispatcherTest::TearDown();
7445 mTouchWindow.clear();
7446 }
7447
chaviw3277faf2021-05-19 16:45:23 -05007448 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7449 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007450 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007451 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007452 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007453 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007454 return window;
7455 }
7456
7457 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7458 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7459 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007460 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007461 // Generate an arbitrary PID based on the UID
7462 window->setOwnerInfo(1777 + (uid % 10000), uid);
7463 return window;
7464 }
7465
7466 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7467 NotifyMotionArgs args =
7468 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7469 ADISPLAY_ID_DEFAULT, points);
7470 mDispatcher->notifyMotion(&args);
7471 }
7472};
7473
7474TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007475 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007476 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007478
7479 touch();
7480
7481 mTouchWindow->assertNoEvents();
7482}
7483
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007484TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007485 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7486 const sp<FakeWindowHandle>& w =
7487 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7489
7490 touch();
7491
7492 mTouchWindow->assertNoEvents();
7493}
7494
7495TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007496 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7497 const sp<FakeWindowHandle>& w =
7498 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7500
7501 touch();
7502
7503 w->assertNoEvents();
7504}
7505
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007506TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007507 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007509
7510 touch();
7511
7512 mTouchWindow->consumeAnyMotionDown();
7513}
7514
7515TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007516 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007517 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007518 w->setFrame(Rect(0, 0, 50, 50));
7519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007520
7521 touch({PointF{100, 100}});
7522
7523 mTouchWindow->consumeAnyMotionDown();
7524}
7525
7526TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007527 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007528 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7530
7531 touch();
7532
7533 mTouchWindow->consumeAnyMotionDown();
7534}
7535
7536TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7537 const sp<FakeWindowHandle>& w =
7538 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007540
7541 touch();
7542
7543 mTouchWindow->consumeAnyMotionDown();
7544}
7545
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007546TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7547 const sp<FakeWindowHandle>& w =
7548 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7550
7551 touch();
7552
7553 w->assertNoEvents();
7554}
7555
7556/**
7557 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7558 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7559 * window, the occluding window will still receive ACTION_OUTSIDE event.
7560 */
7561TEST_F(InputDispatcherUntrustedTouchesTest,
7562 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7563 const sp<FakeWindowHandle>& w =
7564 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007565 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7567
7568 touch();
7569
7570 w->consumeMotionOutside();
7571}
7572
7573TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7574 const sp<FakeWindowHandle>& w =
7575 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007576 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7578
7579 touch();
7580
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007581 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007582}
7583
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007584TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007585 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007586 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7587 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7589
7590 touch();
7591
7592 mTouchWindow->consumeAnyMotionDown();
7593}
7594
7595TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7596 const sp<FakeWindowHandle>& w =
7597 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7598 MAXIMUM_OBSCURING_OPACITY);
7599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007600
7601 touch();
7602
7603 mTouchWindow->consumeAnyMotionDown();
7604}
7605
7606TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007607 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007608 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7609 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7611
7612 touch();
7613
7614 mTouchWindow->assertNoEvents();
7615}
7616
7617TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7618 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7619 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007620 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7621 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007622 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007623 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7624 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7626
7627 touch();
7628
7629 mTouchWindow->assertNoEvents();
7630}
7631
7632TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7633 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7634 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007635 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7636 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007637 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007638 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7639 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7641
7642 touch();
7643
7644 mTouchWindow->consumeAnyMotionDown();
7645}
7646
7647TEST_F(InputDispatcherUntrustedTouchesTest,
7648 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7649 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007650 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7651 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007652 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007653 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7654 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7656
7657 touch();
7658
7659 mTouchWindow->consumeAnyMotionDown();
7660}
7661
7662TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7663 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007664 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7665 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007666 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007667 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7668 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007670
7671 touch();
7672
7673 mTouchWindow->assertNoEvents();
7674}
7675
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007676TEST_F(InputDispatcherUntrustedTouchesTest,
7677 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7678 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007679 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7680 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007681 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007682 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7683 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7685
7686 touch();
7687
7688 mTouchWindow->assertNoEvents();
7689}
7690
7691TEST_F(InputDispatcherUntrustedTouchesTest,
7692 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7693 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007694 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7695 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007696 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007697 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7698 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7700
7701 touch();
7702
7703 mTouchWindow->consumeAnyMotionDown();
7704}
7705
7706TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7707 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007708 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7709 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007710 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7711
7712 touch();
7713
7714 mTouchWindow->consumeAnyMotionDown();
7715}
7716
7717TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7718 const sp<FakeWindowHandle>& w =
7719 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7721
7722 touch();
7723
7724 mTouchWindow->consumeAnyMotionDown();
7725}
7726
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007727TEST_F(InputDispatcherUntrustedTouchesTest,
7728 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7729 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7730 const sp<FakeWindowHandle>& w =
7731 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7733
7734 touch();
7735
7736 mTouchWindow->assertNoEvents();
7737}
7738
7739TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7740 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7741 const sp<FakeWindowHandle>& w =
7742 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7744
7745 touch();
7746
7747 mTouchWindow->consumeAnyMotionDown();
7748}
7749
7750TEST_F(InputDispatcherUntrustedTouchesTest,
7751 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7752 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7753 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007754 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7755 OPACITY_ABOVE_THRESHOLD);
7756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7757
7758 touch();
7759
7760 mTouchWindow->consumeAnyMotionDown();
7761}
7762
7763TEST_F(InputDispatcherUntrustedTouchesTest,
7764 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7765 const sp<FakeWindowHandle>& w1 =
7766 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7767 OPACITY_BELOW_THRESHOLD);
7768 const sp<FakeWindowHandle>& w2 =
7769 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7770 OPACITY_BELOW_THRESHOLD);
7771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7772
7773 touch();
7774
7775 mTouchWindow->assertNoEvents();
7776}
7777
7778/**
7779 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7780 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7781 * (which alone would result in allowing touches) does not affect the blocking behavior.
7782 */
7783TEST_F(InputDispatcherUntrustedTouchesTest,
7784 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7785 const sp<FakeWindowHandle>& wB =
7786 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7787 OPACITY_BELOW_THRESHOLD);
7788 const sp<FakeWindowHandle>& wC =
7789 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7790 OPACITY_BELOW_THRESHOLD);
7791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7792
7793 touch();
7794
7795 mTouchWindow->assertNoEvents();
7796}
7797
7798/**
7799 * This test is testing that a window from a different UID but with same application token doesn't
7800 * block the touch. Apps can share the application token for close UI collaboration for example.
7801 */
7802TEST_F(InputDispatcherUntrustedTouchesTest,
7803 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7804 const sp<FakeWindowHandle>& w =
7805 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7806 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7808
7809 touch();
7810
7811 mTouchWindow->consumeAnyMotionDown();
7812}
7813
arthurhungb89ccb02020-12-30 16:19:01 +08007814class InputDispatcherDragTests : public InputDispatcherTest {
7815protected:
7816 std::shared_ptr<FakeApplicationHandle> mApp;
7817 sp<FakeWindowHandle> mWindow;
7818 sp<FakeWindowHandle> mSecondWindow;
7819 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007820 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007821 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7822 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007823
7824 void SetUp() override {
7825 InputDispatcherTest::SetUp();
7826 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007827 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007828 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007829
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007830 mSecondWindow =
7831 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007832 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007833
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007834 mSpyWindow =
7835 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007836 mSpyWindow->setSpy(true);
7837 mSpyWindow->setTrustedOverlay(true);
7838 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7839
arthurhungb89ccb02020-12-30 16:19:01 +08007840 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007842 }
7843
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007844 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7845 switch (fromSource) {
7846 case AINPUT_SOURCE_TOUCHSCREEN:
7847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7848 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7849 ADISPLAY_ID_DEFAULT, {50, 50}))
7850 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7851 break;
7852 case AINPUT_SOURCE_STYLUS:
7853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7854 injectMotionEvent(
7855 mDispatcher,
7856 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7857 AINPUT_SOURCE_STYLUS)
7858 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7859 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7860 .x(50)
7861 .y(50))
7862 .build()));
7863 break;
7864 case AINPUT_SOURCE_MOUSE:
7865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7866 injectMotionEvent(
7867 mDispatcher,
7868 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7869 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7870 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7871 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7872 .x(50)
7873 .y(50))
7874 .build()));
7875 break;
7876 default:
7877 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7878 }
arthurhungb89ccb02020-12-30 16:19:01 +08007879
7880 // Window should receive motion event.
7881 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007882 // Spy window should also receive motion event
7883 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007884 }
7885
7886 // Start performing drag, we will create a drag window and transfer touch to it.
7887 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7888 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007889 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007890 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007891 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007892 }
arthurhungb89ccb02020-12-30 16:19:01 +08007893
7894 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007895 mDragWindow =
7896 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007897 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007898 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007899 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007900
7901 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007902 bool transferred =
7903 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007904 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007905 if (transferred) {
7906 mWindow->consumeMotionCancel();
7907 mDragWindow->consumeMotionDown();
7908 }
7909 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007910 }
7911};
7912
7913TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007914 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007915
7916 // Move on window.
7917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7918 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7919 ADISPLAY_ID_DEFAULT, {50, 50}))
7920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7921 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7922 mWindow->consumeDragEvent(false, 50, 50);
7923 mSecondWindow->assertNoEvents();
7924
7925 // Move to another window.
7926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7927 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7928 ADISPLAY_ID_DEFAULT, {150, 50}))
7929 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7930 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7931 mWindow->consumeDragEvent(true, 150, 50);
7932 mSecondWindow->consumeDragEvent(false, 50, 50);
7933
7934 // Move back to original window.
7935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7936 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7937 ADISPLAY_ID_DEFAULT, {50, 50}))
7938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7939 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7940 mWindow->consumeDragEvent(false, 50, 50);
7941 mSecondWindow->consumeDragEvent(true, -50, 50);
7942
7943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7944 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7946 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7947 mWindow->assertNoEvents();
7948 mSecondWindow->assertNoEvents();
7949}
7950
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007951TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007952 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007953
7954 // No cancel event after drag start
7955 mSpyWindow->assertNoEvents();
7956
7957 const MotionEvent secondFingerDownEvent =
7958 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7959 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007960 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7961 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007962 .build();
7963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7964 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7965 InputEventInjectionSync::WAIT_FOR_RESULT))
7966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7967
7968 // Receives cancel for first pointer after next pointer down
7969 mSpyWindow->consumeMotionCancel();
7970 mSpyWindow->consumeMotionDown();
7971
7972 mSpyWindow->assertNoEvents();
7973}
7974
arthurhungf452d0b2021-01-06 00:19:52 +08007975TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007976 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007977
7978 // Move on window.
7979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7980 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7981 ADISPLAY_ID_DEFAULT, {50, 50}))
7982 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7983 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7984 mWindow->consumeDragEvent(false, 50, 50);
7985 mSecondWindow->assertNoEvents();
7986
7987 // Move to another window.
7988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7989 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7990 ADISPLAY_ID_DEFAULT, {150, 50}))
7991 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7992 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7993 mWindow->consumeDragEvent(true, 150, 50);
7994 mSecondWindow->consumeDragEvent(false, 50, 50);
7995
7996 // drop to another window.
7997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7998 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7999 {150, 50}))
8000 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8001 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8002 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8003 mWindow->assertNoEvents();
8004 mSecondWindow->assertNoEvents();
8005}
8006
arthurhung6d4bed92021-03-17 11:59:33 +08008007TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008008 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08008009
8010 // Move on window and keep button pressed.
8011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8012 injectMotionEvent(mDispatcher,
8013 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8014 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
8015 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8016 .x(50)
8017 .y(50))
8018 .build()))
8019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8020 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8021 mWindow->consumeDragEvent(false, 50, 50);
8022 mSecondWindow->assertNoEvents();
8023
8024 // Move to another window and release button, expect to drop item.
8025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8026 injectMotionEvent(mDispatcher,
8027 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8028 .buttonState(0)
8029 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8030 .x(150)
8031 .y(50))
8032 .build()))
8033 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8034 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8035 mWindow->assertNoEvents();
8036 mSecondWindow->assertNoEvents();
8037 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8038
8039 // nothing to the window.
8040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8041 injectMotionEvent(mDispatcher,
8042 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
8043 .buttonState(0)
8044 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8045 .x(150)
8046 .y(50))
8047 .build()))
8048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8049 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8050 mWindow->assertNoEvents();
8051 mSecondWindow->assertNoEvents();
8052}
8053
Arthur Hung54745652022-04-20 07:17:41 +00008054TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008055 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08008056
8057 // Set second window invisible.
8058 mSecondWindow->setVisible(false);
8059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
8060
8061 // Move on window.
8062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8063 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8064 ADISPLAY_ID_DEFAULT, {50, 50}))
8065 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8066 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8067 mWindow->consumeDragEvent(false, 50, 50);
8068 mSecondWindow->assertNoEvents();
8069
8070 // Move to another window.
8071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8072 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8073 ADISPLAY_ID_DEFAULT, {150, 50}))
8074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8075 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8076 mWindow->consumeDragEvent(true, 150, 50);
8077 mSecondWindow->assertNoEvents();
8078
8079 // drop to another window.
8080 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8081 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8082 {150, 50}))
8083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8084 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8085 mFakePolicy->assertDropTargetEquals(nullptr);
8086 mWindow->assertNoEvents();
8087 mSecondWindow->assertNoEvents();
8088}
8089
Arthur Hung54745652022-04-20 07:17:41 +00008090TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008091 // Ensure window could track pointerIds if it didn't support split touch.
8092 mWindow->setPreventSplitting(true);
8093
Arthur Hung54745652022-04-20 07:17:41 +00008094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8095 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8096 {50, 50}))
8097 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8098 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8099
8100 const MotionEvent secondFingerDownEvent =
8101 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8102 .displayId(ADISPLAY_ID_DEFAULT)
8103 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008104 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8105 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008106 .build();
8107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8108 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8109 InputEventInjectionSync::WAIT_FOR_RESULT))
8110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008111 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00008112
8113 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008114 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008115}
8116
8117TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
8118 // First down on second window.
8119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8120 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8121 {150, 50}))
8122 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8123
8124 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8125
8126 // Second down on first window.
8127 const MotionEvent secondFingerDownEvent =
8128 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8129 .displayId(ADISPLAY_ID_DEFAULT)
8130 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008131 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8132 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008133 .build();
8134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8135 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8136 InputEventInjectionSync::WAIT_FOR_RESULT))
8137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8138 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8139
8140 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008141 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008142
8143 // Move on window.
8144 const MotionEvent secondFingerMoveEvent =
8145 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8146 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008147 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8148 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008149 .build();
8150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8151 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8152 InputEventInjectionSync::WAIT_FOR_RESULT));
8153 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8154 mWindow->consumeDragEvent(false, 50, 50);
8155 mSecondWindow->consumeMotionMove();
8156
8157 // Release the drag pointer should perform drop.
8158 const MotionEvent secondFingerUpEvent =
8159 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8160 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008161 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8162 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008163 .build();
8164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8165 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8166 InputEventInjectionSync::WAIT_FOR_RESULT));
8167 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8168 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8169 mWindow->assertNoEvents();
8170 mSecondWindow->consumeMotionMove();
8171}
8172
Arthur Hung3915c1f2022-05-31 07:17:17 +00008173TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008174 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008175
8176 // Update window of second display.
8177 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008178 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008179 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8180
8181 // Let second display has a touch state.
8182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8183 injectMotionEvent(mDispatcher,
8184 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8185 AINPUT_SOURCE_TOUCHSCREEN)
8186 .displayId(SECOND_DISPLAY_ID)
8187 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8188 .x(100)
8189 .y(100))
8190 .build()));
8191 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008192 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008193 // Update window again.
8194 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8195
8196 // Move on window.
8197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8198 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8199 ADISPLAY_ID_DEFAULT, {50, 50}))
8200 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8201 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8202 mWindow->consumeDragEvent(false, 50, 50);
8203 mSecondWindow->assertNoEvents();
8204
8205 // Move to another window.
8206 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8207 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8208 ADISPLAY_ID_DEFAULT, {150, 50}))
8209 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8210 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8211 mWindow->consumeDragEvent(true, 150, 50);
8212 mSecondWindow->consumeDragEvent(false, 50, 50);
8213
8214 // drop to another window.
8215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8216 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8217 {150, 50}))
8218 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8219 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8220 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8221 mWindow->assertNoEvents();
8222 mSecondWindow->assertNoEvents();
8223}
8224
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008225TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8226 startDrag(true, AINPUT_SOURCE_MOUSE);
8227 // Move on window.
8228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8229 injectMotionEvent(mDispatcher,
8230 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8231 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8232 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8233 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8234 .x(50)
8235 .y(50))
8236 .build()))
8237 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8238 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8239 mWindow->consumeDragEvent(false, 50, 50);
8240 mSecondWindow->assertNoEvents();
8241
8242 // Move to another window.
8243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8244 injectMotionEvent(mDispatcher,
8245 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8246 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8247 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8248 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8249 .x(150)
8250 .y(50))
8251 .build()))
8252 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8253 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8254 mWindow->consumeDragEvent(true, 150, 50);
8255 mSecondWindow->consumeDragEvent(false, 50, 50);
8256
8257 // drop to another window.
8258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8259 injectMotionEvent(mDispatcher,
8260 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8261 .buttonState(0)
8262 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8263 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8264 .x(150)
8265 .y(50))
8266 .build()))
8267 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8268 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8269 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8270 mWindow->assertNoEvents();
8271 mSecondWindow->assertNoEvents();
8272}
8273
Vishnu Nair062a8672021-09-03 16:07:44 -07008274class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8275
8276TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8277 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008278 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8279 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008280 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008281 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8282 window->setFocusable(true);
8283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8284 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008285 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008286
8287 // With the flag set, window should not get any input
8288 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8289 mDispatcher->notifyKey(&keyArgs);
8290 window->assertNoEvents();
8291
8292 NotifyMotionArgs motionArgs =
8293 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8294 ADISPLAY_ID_DEFAULT);
8295 mDispatcher->notifyMotion(&motionArgs);
8296 window->assertNoEvents();
8297
8298 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008299 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8301
8302 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8303 mDispatcher->notifyKey(&keyArgs);
8304 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8305
8306 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8307 ADISPLAY_ID_DEFAULT);
8308 mDispatcher->notifyMotion(&motionArgs);
8309 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8310 window->assertNoEvents();
8311}
8312
8313TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8314 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8315 std::make_shared<FakeApplicationHandle>();
8316 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008317 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8318 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008319 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8320 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008321 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008322 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008323 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8324 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008325 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008326 window->setOwnerInfo(222, 222);
8327 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8328 window->setFocusable(true);
8329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, 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->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, 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, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8356 window->assertNoEvents();
8357}
8358
8359TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
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 // When the window is no longer obscured because it went on top, it should get input
8391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8392
8393 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8394 mDispatcher->notifyKey(&keyArgs);
8395 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8396
8397 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8398 ADISPLAY_ID_DEFAULT);
8399 mDispatcher->notifyMotion(&motionArgs);
8400 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8401 window->assertNoEvents();
8402}
8403
Antonio Kantekf16f2832021-09-28 04:39:20 +00008404class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8405protected:
8406 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008407 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008408 sp<FakeWindowHandle> mWindow;
8409 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008410 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008411
8412 void SetUp() override {
8413 InputDispatcherTest::SetUp();
8414
8415 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008416 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008417 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008418 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008419 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008420 mSecondWindow =
8421 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008422 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008423 mThirdWindow =
8424 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8425 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8426 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008427
8428 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8430 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8431 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008432 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008433
Antonio Kantek15beb512022-06-13 22:35:41 +00008434 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008435 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008436 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008437 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8438 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008439 mThirdWindow->assertNoEvents();
8440 }
8441
8442 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8443 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008444 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008445 SECOND_DISPLAY_ID)) {
8446 mWindow->assertNoEvents();
8447 mSecondWindow->assertNoEvents();
8448 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008449 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008450 }
8451
Antonio Kantek15beb512022-06-13 22:35:41 +00008452 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8453 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008454 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8455 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008456 mWindow->consumeTouchModeEvent(inTouchMode);
8457 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008458 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008459 }
8460};
8461
Antonio Kantek26defcf2022-02-08 01:12:27 +00008462TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008463 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008464 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8465 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008466 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008467}
8468
Antonio Kantek26defcf2022-02-08 01:12:27 +00008469TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8470 const WindowInfo& windowInfo = *mWindow->getInfo();
8471 int32_t ownerPid = windowInfo.ownerPid;
8472 int32_t ownerUid = windowInfo.ownerUid;
8473 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8474 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008475 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008476 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008477 mWindow->assertNoEvents();
8478 mSecondWindow->assertNoEvents();
8479}
8480
8481TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8482 const WindowInfo& windowInfo = *mWindow->getInfo();
8483 int32_t ownerPid = windowInfo.ownerPid;
8484 int32_t ownerUid = windowInfo.ownerUid;
8485 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008486 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008487 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008488}
8489
Antonio Kantekf16f2832021-09-28 04:39:20 +00008490TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008491 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008492 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8493 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008494 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008495 mWindow->assertNoEvents();
8496 mSecondWindow->assertNoEvents();
8497}
8498
Antonio Kantek15beb512022-06-13 22:35:41 +00008499TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8500 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8501 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8502 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008503 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008504 mWindow->assertNoEvents();
8505 mSecondWindow->assertNoEvents();
8506 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8507}
8508
Antonio Kantek48710e42022-03-24 14:19:30 -07008509TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8510 // Interact with the window first.
8511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8512 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8513 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8514
8515 // Then remove focus.
8516 mWindow->setFocusable(false);
8517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8518
8519 // Assert that caller can switch touch mode by owning one of the last interacted window.
8520 const WindowInfo& windowInfo = *mWindow->getInfo();
8521 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8522 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008523 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008524}
8525
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008526class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8527public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008528 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008529 std::shared_ptr<FakeApplicationHandle> application =
8530 std::make_shared<FakeApplicationHandle>();
8531 std::string name = "Fake Spy ";
8532 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008533 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8534 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008535 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008536 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008537 return spy;
8538 }
8539
8540 sp<FakeWindowHandle> createForeground() {
8541 std::shared_ptr<FakeApplicationHandle> application =
8542 std::make_shared<FakeApplicationHandle>();
8543 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008544 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8545 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008546 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008547 return window;
8548 }
8549
8550private:
8551 int mSpyCount{0};
8552};
8553
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008554using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008555/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008556 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8557 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008558TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8559 ScopedSilentDeath _silentDeath;
8560
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008561 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008562 spy->setTrustedOverlay(false);
8563 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8564 ".* not a trusted overlay");
8565}
8566
8567/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008568 * Input injection into a display with a spy window but no foreground windows should succeed.
8569 */
8570TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008571 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8573
8574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8575 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8577 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8578}
8579
8580/**
8581 * Verify the order in which different input windows receive events. The touched foreground window
8582 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8583 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8584 * receive events before ones belows it.
8585 *
8586 * Here, we set up a scenario with four windows in the following Z order from the top:
8587 * spy1, spy2, window, spy3.
8588 * We then inject an event and verify that the foreground "window" receives it first, followed by
8589 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8590 * window.
8591 */
8592TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8593 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008594 auto spy1 = createSpy();
8595 auto spy2 = createSpy();
8596 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8598 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8599 const size_t numChannels = channels.size();
8600
Michael Wright8e9a8562022-02-09 13:44:29 +00008601 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008602 if (!epollFd.ok()) {
8603 FAIL() << "Failed to create epoll fd";
8604 }
8605
8606 for (size_t i = 0; i < numChannels; i++) {
8607 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8608 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8609 FAIL() << "Failed to add fd to epoll";
8610 }
8611 }
8612
8613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8615 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8616
8617 std::vector<size_t> eventOrder;
8618 std::vector<struct epoll_event> events(numChannels);
8619 for (;;) {
8620 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8621 (100ms).count());
8622 if (nFds < 0) {
8623 FAIL() << "Failed to call epoll_wait";
8624 }
8625 if (nFds == 0) {
8626 break; // epoll_wait timed out
8627 }
8628 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008629 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008630 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008631 channels[i]->consumeMotionDown();
8632 }
8633 }
8634
8635 // Verify the order in which the events were received.
8636 EXPECT_EQ(3u, eventOrder.size());
8637 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8638 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8639 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8640}
8641
8642/**
8643 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8644 */
8645TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8646 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008647 auto spy = createSpy();
8648 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8650
8651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8652 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8654 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8655 spy->assertNoEvents();
8656}
8657
8658/**
8659 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8660 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8661 * to the window.
8662 */
8663TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8664 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008665 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008666 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8668
8669 // Inject an event outside the spy window's touchable region.
8670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8673 window->consumeMotionDown();
8674 spy->assertNoEvents();
8675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8676 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8677 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8678 window->consumeMotionUp();
8679 spy->assertNoEvents();
8680
8681 // Inject an event inside the spy window's touchable region.
8682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8683 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8684 {5, 10}))
8685 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8686 window->consumeMotionDown();
8687 spy->consumeMotionDown();
8688}
8689
8690/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008691 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008692 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008693 */
8694TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8695 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008696 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008697 auto spy = createSpy();
8698 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008699 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008700 spy->setFrame(Rect{0, 0, 20, 20});
8701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8702
8703 // Inject an event outside the spy window's frame and touchable region.
8704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008705 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8706 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008707 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8708 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008709 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008710}
8711
8712/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008713 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8714 * pointers that are down within its bounds.
8715 */
8716TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8717 auto windowLeft = createForeground();
8718 windowLeft->setFrame({0, 0, 100, 200});
8719 auto windowRight = createForeground();
8720 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008721 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008722 spy->setFrame({0, 0, 200, 200});
8723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8724
8725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8727 {50, 50}))
8728 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8729 windowLeft->consumeMotionDown();
8730 spy->consumeMotionDown();
8731
8732 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008733 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008734 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008735 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8736 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008737 .build();
8738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8739 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8740 InputEventInjectionSync::WAIT_FOR_RESULT))
8741 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8742 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008743 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008744}
8745
8746/**
8747 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8748 * the spy should receive the second pointer with ACTION_DOWN.
8749 */
8750TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8751 auto window = createForeground();
8752 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008753 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008754 spyRight->setFrame({100, 0, 200, 200});
8755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8756
8757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8758 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8759 {50, 50}))
8760 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8761 window->consumeMotionDown();
8762 spyRight->assertNoEvents();
8763
8764 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008765 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008766 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008767 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8768 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008769 .build();
8770 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8771 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8772 InputEventInjectionSync::WAIT_FOR_RESULT))
8773 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008774 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008775 spyRight->consumeMotionDown();
8776}
8777
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008778/**
8779 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8780 * windows should be allowed to control split touch.
8781 */
8782TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008783 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008784 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008785 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008786 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008787
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008788 auto window = createForeground();
8789 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008790
8791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8792
8793 // First finger down, no window touched.
8794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8795 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8796 {100, 200}))
8797 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8798 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8799 window->assertNoEvents();
8800
8801 // Second finger down on window, the window should receive touch down.
8802 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008803 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008804 .displayId(ADISPLAY_ID_DEFAULT)
8805 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008806 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8807 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008808 .build();
8809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8810 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8811 InputEventInjectionSync::WAIT_FOR_RESULT))
8812 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8813
8814 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008815 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008816}
8817
8818/**
8819 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8820 * do not receive key events.
8821 */
8822TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008823 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008824 spy->setFocusable(false);
8825
8826 auto window = createForeground();
8827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8828 setFocusedWindow(window);
8829 window->consumeFocusEvent(true);
8830
8831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8832 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8833 window->consumeKeyDown(ADISPLAY_ID_NONE);
8834
8835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8836 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8837 window->consumeKeyUp(ADISPLAY_ID_NONE);
8838
8839 spy->assertNoEvents();
8840}
8841
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008842using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8843
8844/**
8845 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8846 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8847 */
8848TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8849 auto window = createForeground();
8850 auto spy1 = createSpy();
8851 auto spy2 = createSpy();
8852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8853
8854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8855 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8857 window->consumeMotionDown();
8858 spy1->consumeMotionDown();
8859 spy2->consumeMotionDown();
8860
8861 // Pilfer pointers from the second spy window.
8862 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8863 spy2->assertNoEvents();
8864 spy1->consumeMotionCancel();
8865 window->consumeMotionCancel();
8866
8867 // The rest of the gesture should only be sent to the second spy window.
8868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8870 ADISPLAY_ID_DEFAULT))
8871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8872 spy2->consumeMotionMove();
8873 spy1->assertNoEvents();
8874 window->assertNoEvents();
8875}
8876
8877/**
8878 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8879 * in the middle of the gesture.
8880 */
8881TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8882 auto window = createForeground();
8883 auto spy = createSpy();
8884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8885
8886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8887 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8888 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8889 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8890 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8891
8892 window->releaseChannel();
8893
8894 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8895
8896 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8897 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8898 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8899 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8900}
8901
8902/**
8903 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8904 * the spy, but not to any other windows.
8905 */
8906TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8907 auto spy = createSpy();
8908 auto window = createForeground();
8909
8910 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8911
8912 // First finger down on the window and the spy.
8913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8914 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8915 {100, 200}))
8916 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8917 spy->consumeMotionDown();
8918 window->consumeMotionDown();
8919
8920 // Spy window pilfers the pointers.
8921 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8922 window->consumeMotionCancel();
8923
8924 // Second finger down on the window and spy, but the window should not receive the pointer down.
8925 const MotionEvent secondFingerDownEvent =
8926 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8927 .displayId(ADISPLAY_ID_DEFAULT)
8928 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008929 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8930 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008931 .build();
8932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8933 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8934 InputEventInjectionSync::WAIT_FOR_RESULT))
8935 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8936
Harry Cutts33476232023-01-30 19:57:29 +00008937 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008938
8939 // Third finger goes down outside all windows, so injection should fail.
8940 const MotionEvent thirdFingerDownEvent =
8941 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8942 .displayId(ADISPLAY_ID_DEFAULT)
8943 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008944 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8945 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8946 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008947 .build();
8948 ASSERT_EQ(InputEventInjectionResult::FAILED,
8949 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8950 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008951 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008952
8953 spy->assertNoEvents();
8954 window->assertNoEvents();
8955}
8956
8957/**
8958 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8959 */
8960TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8961 auto spy = createSpy();
8962 spy->setFrame(Rect(0, 0, 100, 100));
8963 auto window = createForeground();
8964 window->setFrame(Rect(0, 0, 200, 200));
8965
8966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8967
8968 // First finger down on the window only
8969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8971 {150, 150}))
8972 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8973 window->consumeMotionDown();
8974
8975 // Second finger down on the spy and window
8976 const MotionEvent secondFingerDownEvent =
8977 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8978 .displayId(ADISPLAY_ID_DEFAULT)
8979 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008980 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8981 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008982 .build();
8983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8984 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8985 InputEventInjectionSync::WAIT_FOR_RESULT))
8986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8987 spy->consumeMotionDown();
8988 window->consumeMotionPointerDown(1);
8989
8990 // Third finger down on the spy and window
8991 const MotionEvent thirdFingerDownEvent =
8992 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8993 .displayId(ADISPLAY_ID_DEFAULT)
8994 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008995 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8996 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8997 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008998 .build();
8999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9000 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
9001 InputEventInjectionSync::WAIT_FOR_RESULT))
9002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9003 spy->consumeMotionPointerDown(1);
9004 window->consumeMotionPointerDown(2);
9005
9006 // Spy window pilfers the pointers.
9007 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9008 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9009 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9010
9011 spy->assertNoEvents();
9012 window->assertNoEvents();
9013}
9014
9015/**
9016 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
9017 * other windows should be canceled. If this results in the cancellation of all pointers for some
9018 * window, then that window should receive ACTION_CANCEL.
9019 */
9020TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
9021 auto spy = createSpy();
9022 spy->setFrame(Rect(0, 0, 100, 100));
9023 auto window = createForeground();
9024 window->setFrame(Rect(0, 0, 200, 200));
9025
9026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9027
9028 // First finger down on both spy and window
9029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9030 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9031 {10, 10}))
9032 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9033 window->consumeMotionDown();
9034 spy->consumeMotionDown();
9035
9036 // Second finger down on the spy and window
9037 const MotionEvent secondFingerDownEvent =
9038 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9039 .displayId(ADISPLAY_ID_DEFAULT)
9040 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009041 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9042 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009043 .build();
9044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9045 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9046 InputEventInjectionSync::WAIT_FOR_RESULT))
9047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9048 spy->consumeMotionPointerDown(1);
9049 window->consumeMotionPointerDown(1);
9050
9051 // Spy window pilfers the pointers.
9052 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9053 window->consumeMotionCancel();
9054
9055 spy->assertNoEvents();
9056 window->assertNoEvents();
9057}
9058
9059/**
9060 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
9061 * be sent to other windows
9062 */
9063TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
9064 auto spy = createSpy();
9065 spy->setFrame(Rect(0, 0, 100, 100));
9066 auto window = createForeground();
9067 window->setFrame(Rect(0, 0, 200, 200));
9068
9069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9070
9071 // First finger down on both window and spy
9072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9073 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9074 {10, 10}))
9075 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9076 window->consumeMotionDown();
9077 spy->consumeMotionDown();
9078
9079 // Spy window pilfers the pointers.
9080 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9081 window->consumeMotionCancel();
9082
9083 // Second finger down on the window only
9084 const MotionEvent secondFingerDownEvent =
9085 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9086 .displayId(ADISPLAY_ID_DEFAULT)
9087 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009088 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9089 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009090 .build();
9091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9092 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9093 InputEventInjectionSync::WAIT_FOR_RESULT))
9094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9095 window->consumeMotionDown();
9096 window->assertNoEvents();
9097
9098 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
9099 spy->consumeMotionMove();
9100 spy->assertNoEvents();
9101}
9102
Prabir Pradhand65552b2021-10-07 11:23:50 -07009103class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
9104public:
9105 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
9106 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9107 std::make_shared<FakeApplicationHandle>();
9108 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009109 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
9110 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009111 overlay->setFocusable(false);
9112 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08009113 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009114 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009115 overlay->setTrustedOverlay(true);
9116
9117 std::shared_ptr<FakeApplicationHandle> application =
9118 std::make_shared<FakeApplicationHandle>();
9119 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009120 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9121 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009122 window->setFocusable(true);
9123 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009124
9125 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9127 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009128 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009129 return {std::move(overlay), std::move(window)};
9130 }
9131
9132 void sendFingerEvent(int32_t action) {
9133 NotifyMotionArgs motionArgs =
9134 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9135 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9136 mDispatcher->notifyMotion(&motionArgs);
9137 }
9138
9139 void sendStylusEvent(int32_t action) {
9140 NotifyMotionArgs motionArgs =
9141 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9142 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9143 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9144 mDispatcher->notifyMotion(&motionArgs);
9145 }
9146};
9147
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009148using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9149
9150TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9151 ScopedSilentDeath _silentDeath;
9152
Prabir Pradhand65552b2021-10-07 11:23:50 -07009153 auto [overlay, window] = setupStylusOverlayScenario();
9154 overlay->setTrustedOverlay(false);
9155 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9156 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9157 ".* not a trusted overlay");
9158}
9159
9160TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9161 auto [overlay, window] = setupStylusOverlayScenario();
9162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9163
9164 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9165 overlay->consumeMotionDown();
9166 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9167 overlay->consumeMotionUp();
9168
9169 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9170 window->consumeMotionDown();
9171 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9172 window->consumeMotionUp();
9173
9174 overlay->assertNoEvents();
9175 window->assertNoEvents();
9176}
9177
9178TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9179 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009180 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9182
9183 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9184 overlay->consumeMotionDown();
9185 window->consumeMotionDown();
9186 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9187 overlay->consumeMotionUp();
9188 window->consumeMotionUp();
9189
9190 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9191 window->consumeMotionDown();
9192 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9193 window->consumeMotionUp();
9194
9195 overlay->assertNoEvents();
9196 window->assertNoEvents();
9197}
9198
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009199/**
9200 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9201 * The scenario is as follows:
9202 * - The stylus interceptor overlay is configured as a spy window.
9203 * - The stylus interceptor spy receives the start of a new stylus gesture.
9204 * - It pilfers pointers and then configures itself to no longer be a spy.
9205 * - The stylus interceptor continues to receive the rest of the gesture.
9206 */
9207TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9208 auto [overlay, window] = setupStylusOverlayScenario();
9209 overlay->setSpy(true);
9210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9211
9212 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9213 overlay->consumeMotionDown();
9214 window->consumeMotionDown();
9215
9216 // The interceptor pilfers the pointers.
9217 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9218 window->consumeMotionCancel();
9219
9220 // The interceptor configures itself so that it is no longer a spy.
9221 overlay->setSpy(false);
9222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9223
9224 // It continues to receive the rest of the stylus gesture.
9225 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9226 overlay->consumeMotionMove();
9227 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9228 overlay->consumeMotionUp();
9229
9230 window->assertNoEvents();
9231}
9232
Prabir Pradhan5735a322022-04-11 17:23:34 +00009233struct User {
9234 int32_t mPid;
9235 int32_t mUid;
9236 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9237 std::unique_ptr<InputDispatcher>& mDispatcher;
9238
9239 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9240 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9241
9242 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9243 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9244 ADISPLAY_ID_DEFAULT, {100, 200},
9245 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9246 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9247 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9248 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9249 }
9250
9251 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009252 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009253 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009254 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009255 mPolicyFlags);
9256 }
9257
9258 sp<FakeWindowHandle> createWindow() const {
9259 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9260 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009261 sp<FakeWindowHandle> window =
9262 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9263 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009264 window->setOwnerInfo(mPid, mUid);
9265 return window;
9266 }
9267};
9268
9269using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9270
9271TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9272 auto owner = User(mDispatcher, 10, 11);
9273 auto window = owner.createWindow();
9274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9275
9276 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9277 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9278 window->consumeMotionDown();
9279
9280 setFocusedWindow(window);
9281 window->consumeFocusEvent(true);
9282
9283 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9284 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9285 window->consumeKeyDown(ADISPLAY_ID_NONE);
9286}
9287
9288TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9289 auto owner = User(mDispatcher, 10, 11);
9290 auto window = owner.createWindow();
9291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9292
9293 auto rando = User(mDispatcher, 20, 21);
9294 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9295 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9296
9297 setFocusedWindow(window);
9298 window->consumeFocusEvent(true);
9299
9300 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9301 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9302 window->assertNoEvents();
9303}
9304
9305TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9306 auto owner = User(mDispatcher, 10, 11);
9307 auto window = owner.createWindow();
9308 auto spy = owner.createWindow();
9309 spy->setSpy(true);
9310 spy->setTrustedOverlay(true);
9311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9312
9313 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9314 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9315 spy->consumeMotionDown();
9316 window->consumeMotionDown();
9317}
9318
9319TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9320 auto owner = User(mDispatcher, 10, 11);
9321 auto window = owner.createWindow();
9322
9323 auto rando = User(mDispatcher, 20, 21);
9324 auto randosSpy = rando.createWindow();
9325 randosSpy->setSpy(true);
9326 randosSpy->setTrustedOverlay(true);
9327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9328
9329 // The event is targeted at owner's window, so injection should succeed, but the spy should
9330 // not receive the event.
9331 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9332 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9333 randosSpy->assertNoEvents();
9334 window->consumeMotionDown();
9335}
9336
9337TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9338 auto owner = User(mDispatcher, 10, 11);
9339 auto window = owner.createWindow();
9340
9341 auto rando = User(mDispatcher, 20, 21);
9342 auto randosSpy = rando.createWindow();
9343 randosSpy->setSpy(true);
9344 randosSpy->setTrustedOverlay(true);
9345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9346
9347 // A user that has injection permission can inject into any window.
9348 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9349 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9350 ADISPLAY_ID_DEFAULT));
9351 randosSpy->consumeMotionDown();
9352 window->consumeMotionDown();
9353
9354 setFocusedWindow(randosSpy);
9355 randosSpy->consumeFocusEvent(true);
9356
9357 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9358 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9359 window->assertNoEvents();
9360}
9361
9362TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9363 auto owner = User(mDispatcher, 10, 11);
9364 auto window = owner.createWindow();
9365
9366 auto rando = User(mDispatcher, 20, 21);
9367 auto randosWindow = rando.createWindow();
9368 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9369 randosWindow->setWatchOutsideTouch(true);
9370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9371
9372 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9373 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9374 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9375 window->consumeMotionDown();
9376 randosWindow->consumeMotionOutside();
9377}
9378
Garfield Tane84e6f92019-08-29 17:28:41 -07009379} // namespace android::inputdispatcher