blob: 7f02a335e4ca63056fb862946623f65e867cf69a [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();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003941 removeAllWindowsAndDisplays();
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003942 }
3943
3944 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3945 gui::DisplayInfo info;
3946 info.displayId = displayId;
3947 info.transform = transform;
3948 mDisplayInfos.push_back(std::move(info));
3949 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3950 }
3951
3952 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3953 mWindowInfos.push_back(*windowHandle->getInfo());
3954 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3955 }
3956
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003957 void removeAllWindowsAndDisplays() {
3958 mDisplayInfos.clear();
3959 mWindowInfos.clear();
3960 }
3961
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003962 // Set up a test scenario where the display has a scaled projection and there are two windows
3963 // on the display.
3964 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3965 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3966 // respectively.
3967 ui::Transform displayTransform;
3968 displayTransform.set(2, 0, 0, 4);
3969 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3970
3971 std::shared_ptr<FakeApplicationHandle> application =
3972 std::make_shared<FakeApplicationHandle>();
3973
3974 // Add two windows to the display. Their frames are represented in the display space.
3975 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003976 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3977 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003978 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3979 addWindow(firstWindow);
3980
3981 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003982 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3983 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003984 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3985 addWindow(secondWindow);
3986 return {std::move(firstWindow), std::move(secondWindow)};
3987 }
3988
3989private:
3990 std::vector<gui::DisplayInfo> mDisplayInfos;
3991 std::vector<gui::WindowInfo> mWindowInfos;
3992};
3993
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003994TEST_F(InputDispatcherDisplayProjectionTest, HitTestCoordinateSpaceConsistency) {
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003995 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3996 // Send down to the first window. The point is represented in the display space. The point is
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00003997 // selected so that if the hit test was performed with the point and the bounds being in
3998 // different coordinate spaces, the event would end up in the incorrect window.
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003999 NotifyMotionArgs downMotionArgs =
4000 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4001 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
4002 mDispatcher->notifyMotion(&downMotionArgs);
4003
4004 firstWindow->consumeMotionDown();
4005 secondWindow->assertNoEvents();
4006}
4007
4008// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
4009// the event should be treated as being in the logical display space.
4010TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
4011 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4012 // Send down to the first window. The point is represented in the logical display space. The
4013 // point is selected so that if the hit test was done in logical display space, then it would
4014 // end up in the incorrect window.
4015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4016 PointF{75 * 2, 55 * 4});
4017
4018 firstWindow->consumeMotionDown();
4019 secondWindow->assertNoEvents();
4020}
4021
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004022// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
4023// event should be treated as being in the logical display space.
4024TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
4025 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4026
4027 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
4028 ui::Transform injectedEventTransform;
4029 injectedEventTransform.set(matrix);
4030 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
4031 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
4032
4033 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
4034 .displayId(ADISPLAY_ID_DEFAULT)
4035 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00004036 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004037 .x(untransformedPoint.x)
4038 .y(untransformedPoint.y))
4039 .build();
4040 event.transform(matrix);
4041
4042 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
4043 InputEventInjectionSync::WAIT_FOR_RESULT);
4044
4045 firstWindow->consumeMotionDown();
4046 secondWindow->assertNoEvents();
4047}
4048
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07004049TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
4050 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
4051
4052 // Send down to the second window.
4053 NotifyMotionArgs downMotionArgs =
4054 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4055 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
4056 mDispatcher->notifyMotion(&downMotionArgs);
4057
4058 firstWindow->assertNoEvents();
4059 const MotionEvent* event = secondWindow->consumeMotion();
4060 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
4061
4062 // Ensure that the events from the "getRaw" API are in logical display coordinates.
4063 EXPECT_EQ(300, event->getRawX(0));
4064 EXPECT_EQ(880, event->getRawY(0));
4065
4066 // Ensure that the x and y values are in the window's coordinate space.
4067 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
4068 // the logical display space. This will be the origin of the window space.
4069 EXPECT_EQ(100, event->getX(0));
4070 EXPECT_EQ(80, event->getY(0));
4071}
4072
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004073/** Ensure consistent behavior of InputDispatcher in all orientations. */
4074class InputDispatcherDisplayOrientationFixture
4075 : public InputDispatcherDisplayProjectionTest,
4076 public ::testing::WithParamInterface<ui::Rotation> {};
4077
4078// This test verifies the touchable region of a window for all rotations of the display by tapping
4079// in different locations on the display, specifically points close to the four corners of a
4080// window.
4081TEST_P(InputDispatcherDisplayOrientationFixture, HitTestInDifferentOrientations) {
4082 constexpr static int32_t displayWidth = 400;
4083 constexpr static int32_t displayHeight = 800;
4084
4085 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4086
4087 const auto rotation = GetParam();
4088
4089 // Set up the display with the specified rotation.
4090 const bool isRotated = rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270;
4091 const int32_t logicalDisplayWidth = isRotated ? displayHeight : displayWidth;
4092 const int32_t logicalDisplayHeight = isRotated ? displayWidth : displayHeight;
4093 const ui::Transform displayTransform(ui::Transform::toRotationFlags(rotation),
4094 logicalDisplayWidth, logicalDisplayHeight);
4095 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
4096
4097 // Create a window with its bounds determined in the logical display.
4098 const Rect frameInLogicalDisplay(100, 100, 200, 300);
4099 const Rect frameInDisplay = displayTransform.inverse().transform(frameInLogicalDisplay);
4100 sp<FakeWindowHandle> window =
4101 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
4102 window->setFrame(frameInDisplay, displayTransform);
4103 addWindow(window);
4104
4105 // The following points in logical display space should be inside the window.
4106 static const std::array<vec2, 4> insidePoints{
4107 {{100, 100}, {199.99, 100}, {100, 299.99}, {199.99, 299.99}}};
4108 for (const auto pointInsideWindow : insidePoints) {
4109 const vec2 p = displayTransform.inverse().transform(pointInsideWindow);
4110 const PointF pointInDisplaySpace{p.x, p.y};
4111 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4112 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4113 mDispatcher->notifyMotion(&down);
4114 window->consumeMotionDown();
4115
4116 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4117 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4118 mDispatcher->notifyMotion(&up);
4119 window->consumeMotionUp();
4120 }
4121
4122 // The following points in logical display space should be outside the window.
4123 static const std::array<vec2, 5> outsidePoints{
4124 {{200, 100}, {100, 300}, {200, 300}, {100, 99.99}, {99.99, 100}}};
4125 for (const auto pointOutsideWindow : outsidePoints) {
4126 const vec2 p = displayTransform.inverse().transform(pointOutsideWindow);
4127 const PointF pointInDisplaySpace{p.x, p.y};
4128 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4129 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4130 mDispatcher->notifyMotion(&down);
4131
4132 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4133 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
4134 mDispatcher->notifyMotion(&up);
4135 }
4136 window->assertNoEvents();
4137}
4138
4139// Run the precision tests for all rotations.
4140INSTANTIATE_TEST_SUITE_P(InputDispatcherDisplayOrientationTests,
4141 InputDispatcherDisplayOrientationFixture,
4142 ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
4143 ui::ROTATION_270),
4144 [](const testing::TestParamInfo<ui::Rotation>& testParamInfo) {
4145 return ftl::enum_string(testParamInfo.param);
4146 });
4147
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004148using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
4149 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004150
4151class TransferTouchFixture : public InputDispatcherTest,
4152 public ::testing::WithParamInterface<TransferFunction> {};
4153
4154TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07004155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004156
4157 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004158 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004159 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4160 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004161 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004162 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004163 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4164 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004165 sp<FakeWindowHandle> wallpaper =
4166 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
4167 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004168 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00004169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004170
4171 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004172 NotifyMotionArgs downMotionArgs =
4173 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4174 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004175 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00004176
Svet Ganov5d3bc372020-01-26 23:11:07 -08004177 // Only the first window should get the down event
4178 firstWindow->consumeMotionDown();
4179 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004180 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004181
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004182 // Transfer touch to the second window
4183 TransferFunction f = GetParam();
4184 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4185 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186 // The first window gets cancel and the second gets down
4187 firstWindow->consumeMotionCancel();
4188 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004189 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190
4191 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004192 NotifyMotionArgs upMotionArgs =
4193 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4194 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195 mDispatcher->notifyMotion(&upMotionArgs);
4196 // The first window gets no events and the second gets up
4197 firstWindow->assertNoEvents();
4198 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004199 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004200}
4201
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004202/**
4203 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
4204 * from. When we have spy windows, there are several windows to choose from: either spy, or the
4205 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
4206 * natural to the user.
4207 * In this test, we are sending a pointer to both spy window and first window. We then try to
4208 * transfer touch to the second window. The dispatcher should identify the first window as the
4209 * one that should lose the gesture, and therefore the action should be to move the gesture from
4210 * the first window to the second.
4211 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
4212 * the other API, as well.
4213 */
4214TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
4215 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4216
4217 // Create a couple of windows + a spy window
4218 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004219 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004220 spyWindow->setTrustedOverlay(true);
4221 spyWindow->setSpy(true);
4222 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004223 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004224 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004225 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004226
4227 // Add the windows to the dispatcher
4228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
4229
4230 // Send down to the first window
4231 NotifyMotionArgs downMotionArgs =
4232 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4233 ADISPLAY_ID_DEFAULT);
4234 mDispatcher->notifyMotion(&downMotionArgs);
4235 // Only the first window and spy should get the down event
4236 spyWindow->consumeMotionDown();
4237 firstWindow->consumeMotionDown();
4238
4239 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
4240 // if f === 'transferTouch'.
4241 TransferFunction f = GetParam();
4242 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4243 ASSERT_TRUE(success);
4244 // The first window gets cancel and the second gets down
4245 firstWindow->consumeMotionCancel();
4246 secondWindow->consumeMotionDown();
4247
4248 // Send up event to the second window
4249 NotifyMotionArgs upMotionArgs =
4250 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4251 ADISPLAY_ID_DEFAULT);
4252 mDispatcher->notifyMotion(&upMotionArgs);
4253 // The first window gets no events and the second+spy get up
4254 firstWindow->assertNoEvents();
4255 spyWindow->consumeMotionUp();
4256 secondWindow->consumeMotionUp();
4257}
4258
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004259TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004261
4262 PointF touchPoint = {10, 10};
4263
4264 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004265 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004266 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4267 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004268 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004269 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004270 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4271 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004272 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004273
4274 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004276
4277 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004278 NotifyMotionArgs downMotionArgs =
4279 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4280 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004281 mDispatcher->notifyMotion(&downMotionArgs);
4282 // Only the first window should get the down event
4283 firstWindow->consumeMotionDown();
4284 secondWindow->assertNoEvents();
4285
4286 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004287 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004288 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004289 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004290 mDispatcher->notifyMotion(&pointerDownMotionArgs);
4291 // Only the first window should get the pointer down event
4292 firstWindow->consumeMotionPointerDown(1);
4293 secondWindow->assertNoEvents();
4294
4295 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004296 TransferFunction f = GetParam();
4297 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4298 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004299 // The first window gets cancel and the second gets down and pointer down
4300 firstWindow->consumeMotionCancel();
4301 secondWindow->consumeMotionDown();
4302 secondWindow->consumeMotionPointerDown(1);
4303
4304 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004305 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004306 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004307 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004308 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4309 // The first window gets nothing and the second gets pointer up
4310 firstWindow->assertNoEvents();
4311 secondWindow->consumeMotionPointerUp(1);
4312
4313 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004314 NotifyMotionArgs upMotionArgs =
4315 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4316 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004317 mDispatcher->notifyMotion(&upMotionArgs);
4318 // The first window gets nothing and the second gets up
4319 firstWindow->assertNoEvents();
4320 secondWindow->consumeMotionUp();
4321}
4322
Arthur Hungc539dbb2022-12-08 07:45:36 +00004323TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
4324 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4325
4326 // Create a couple of windows
4327 sp<FakeWindowHandle> firstWindow =
4328 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4329 ADISPLAY_ID_DEFAULT);
4330 firstWindow->setDupTouchToWallpaper(true);
4331 sp<FakeWindowHandle> secondWindow =
4332 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4333 ADISPLAY_ID_DEFAULT);
4334 secondWindow->setDupTouchToWallpaper(true);
4335
4336 sp<FakeWindowHandle> wallpaper1 =
4337 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
4338 wallpaper1->setIsWallpaper(true);
4339
4340 sp<FakeWindowHandle> wallpaper2 =
4341 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
4342 wallpaper2->setIsWallpaper(true);
4343 // Add the windows to the dispatcher
4344 mDispatcher->setInputWindows(
4345 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
4346
4347 // Send down to the first window
4348 NotifyMotionArgs downMotionArgs =
4349 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4350 ADISPLAY_ID_DEFAULT);
4351 mDispatcher->notifyMotion(&downMotionArgs);
4352
4353 // Only the first window should get the down event
4354 firstWindow->consumeMotionDown();
4355 secondWindow->assertNoEvents();
4356 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4357 wallpaper2->assertNoEvents();
4358
4359 // Transfer touch focus to the second window
4360 TransferFunction f = GetParam();
4361 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
4362 ASSERT_TRUE(success);
4363
4364 // The first window gets cancel and the second gets down
4365 firstWindow->consumeMotionCancel();
4366 secondWindow->consumeMotionDown();
4367 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4368 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4369
4370 // Send up event to the second window
4371 NotifyMotionArgs upMotionArgs =
4372 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4373 ADISPLAY_ID_DEFAULT);
4374 mDispatcher->notifyMotion(&upMotionArgs);
4375 // The first window gets no events and the second gets up
4376 firstWindow->assertNoEvents();
4377 secondWindow->consumeMotionUp();
4378 wallpaper1->assertNoEvents();
4379 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
4380}
4381
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004382// For the cases of single pointer touch and two pointers non-split touch, the api's
4383// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
4384// for the case where there are multiple pointers split across several windows.
4385INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
4386 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004387 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4388 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004389 return dispatcher->transferTouch(destChannelToken,
4390 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004391 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004392 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
4393 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004394 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00004395 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004396 }));
4397
Svet Ganov5d3bc372020-01-26 23:11:07 -08004398TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07004399 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08004400
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004401 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004402 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4403 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004404 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004405
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004406 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004407 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4408 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004409 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08004410
4411 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00004412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004413
4414 PointF pointInFirst = {300, 200};
4415 PointF pointInSecond = {300, 600};
4416
4417 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004418 NotifyMotionArgs firstDownMotionArgs =
4419 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4420 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004421 mDispatcher->notifyMotion(&firstDownMotionArgs);
4422 // Only the first window should get the down event
4423 firstWindow->consumeMotionDown();
4424 secondWindow->assertNoEvents();
4425
4426 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004427 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004428 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004429 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004430 mDispatcher->notifyMotion(&secondDownMotionArgs);
4431 // The first window gets a move and the second a down
4432 firstWindow->consumeMotionMove();
4433 secondWindow->consumeMotionDown();
4434
4435 // Transfer touch focus to the second window
4436 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
4437 // The first window gets cancel and the new gets pointer down (it already saw down)
4438 firstWindow->consumeMotionCancel();
4439 secondWindow->consumeMotionPointerDown(1);
4440
4441 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004442 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004443 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004444 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08004445 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4446 // The first window gets nothing and the second gets pointer up
4447 firstWindow->assertNoEvents();
4448 secondWindow->consumeMotionPointerUp(1);
4449
4450 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004451 NotifyMotionArgs upMotionArgs =
4452 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4453 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004454 mDispatcher->notifyMotion(&upMotionArgs);
4455 // The first window gets nothing and the second gets up
4456 firstWindow->assertNoEvents();
4457 secondWindow->consumeMotionUp();
4458}
4459
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004460// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
4461// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
4462// touch is not supported, so the touch should continue on those windows and the transferred-to
4463// window should get nothing.
4464TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
4465 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4466
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004467 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004468 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4469 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004470 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004471
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004472 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004473 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4474 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004475 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004476
4477 // Add the windows to the dispatcher
4478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4479
4480 PointF pointInFirst = {300, 200};
4481 PointF pointInSecond = {300, 600};
4482
4483 // Send down to the first window
4484 NotifyMotionArgs firstDownMotionArgs =
4485 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4486 ADISPLAY_ID_DEFAULT, {pointInFirst});
4487 mDispatcher->notifyMotion(&firstDownMotionArgs);
4488 // Only the first window should get the down event
4489 firstWindow->consumeMotionDown();
4490 secondWindow->assertNoEvents();
4491
4492 // Send down to the second window
4493 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004494 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004495 {pointInFirst, pointInSecond});
4496 mDispatcher->notifyMotion(&secondDownMotionArgs);
4497 // The first window gets a move and the second a down
4498 firstWindow->consumeMotionMove();
4499 secondWindow->consumeMotionDown();
4500
4501 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004502 const bool transferred =
4503 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004504 // The 'transferTouch' call should not succeed, because there are 2 touched windows
4505 ASSERT_FALSE(transferred);
4506 firstWindow->assertNoEvents();
4507 secondWindow->assertNoEvents();
4508
4509 // The rest of the dispatch should proceed as normal
4510 // Send pointer up to the second window
4511 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004512 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004513 {pointInFirst, pointInSecond});
4514 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4515 // The first window gets MOVE and the second gets pointer up
4516 firstWindow->consumeMotionMove();
4517 secondWindow->consumeMotionUp();
4518
4519 // Send up event to the first window
4520 NotifyMotionArgs upMotionArgs =
4521 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4522 ADISPLAY_ID_DEFAULT);
4523 mDispatcher->notifyMotion(&upMotionArgs);
4524 // The first window gets nothing and the second gets up
4525 firstWindow->consumeMotionUp();
4526 secondWindow->assertNoEvents();
4527}
4528
Arthur Hungabbb9d82021-09-01 14:52:30 +00004529// This case will create two windows and one mirrored window on the default display and mirror
4530// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
4531// the windows info of second display before default display.
4532TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
4533 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4534 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004535 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004536 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004537 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004538 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004539 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004540
4541 sp<FakeWindowHandle> mirrorWindowInPrimary =
4542 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4543 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004544
4545 sp<FakeWindowHandle> firstWindowInSecondary =
4546 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4547 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004548
4549 sp<FakeWindowHandle> secondWindowInSecondary =
4550 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4551 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004552
4553 // Update window info, let it find window handle of second display first.
4554 mDispatcher->setInputWindows(
4555 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4556 {ADISPLAY_ID_DEFAULT,
4557 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4558
4559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4560 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4561 {50, 50}))
4562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4563
4564 // Window should receive motion event.
4565 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4566
4567 // Transfer touch focus
4568 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
4569 secondWindowInPrimary->getToken()));
4570 // The first window gets cancel.
4571 firstWindowInPrimary->consumeMotionCancel();
4572 secondWindowInPrimary->consumeMotionDown();
4573
4574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4575 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4576 ADISPLAY_ID_DEFAULT, {150, 50}))
4577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4578 firstWindowInPrimary->assertNoEvents();
4579 secondWindowInPrimary->consumeMotionMove();
4580
4581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4582 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4583 {150, 50}))
4584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4585 firstWindowInPrimary->assertNoEvents();
4586 secondWindowInPrimary->consumeMotionUp();
4587}
4588
4589// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
4590// 'transferTouch' api.
4591TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
4592 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4593 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004594 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004595 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004596 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004597 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00004598 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004599
4600 sp<FakeWindowHandle> mirrorWindowInPrimary =
4601 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
4602 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004603
4604 sp<FakeWindowHandle> firstWindowInSecondary =
4605 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4606 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004607
4608 sp<FakeWindowHandle> secondWindowInSecondary =
4609 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
4610 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004611
4612 // Update window info, let it find window handle of second display first.
4613 mDispatcher->setInputWindows(
4614 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
4615 {ADISPLAY_ID_DEFAULT,
4616 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
4617
4618 // Touch on second display.
4619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4620 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
4621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4622
4623 // Window should receive motion event.
4624 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4625
4626 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07004627 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00004628
4629 // The first window gets cancel.
4630 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4631 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4632
4633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4634 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4635 SECOND_DISPLAY_ID, {150, 50}))
4636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4637 firstWindowInPrimary->assertNoEvents();
4638 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4639
4640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4641 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4642 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4643 firstWindowInPrimary->assertNoEvents();
4644 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4645}
4646
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004647TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004649 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4650 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004651
Vishnu Nair47074b82020-08-14 11:54:47 -07004652 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004654 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004655
4656 window->consumeFocusEvent(true);
4657
4658 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4659 mDispatcher->notifyKey(&keyArgs);
4660
4661 // Window should receive key down event.
4662 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4663}
4664
4665TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004667 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4668 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004669
Arthur Hung72d8dc32020-03-28 00:48:39 +00004670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004671
4672 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4673 mDispatcher->notifyKey(&keyArgs);
4674 mDispatcher->waitForIdle();
4675
4676 window->assertNoEvents();
4677}
4678
4679// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4680TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004681 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004682 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4683 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004684
Arthur Hung72d8dc32020-03-28 00:48:39 +00004685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004686
4687 // Send key
4688 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4689 mDispatcher->notifyKey(&keyArgs);
4690 // Send motion
4691 NotifyMotionArgs motionArgs =
4692 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4693 ADISPLAY_ID_DEFAULT);
4694 mDispatcher->notifyMotion(&motionArgs);
4695
4696 // Window should receive only the motion event
4697 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4698 window->assertNoEvents(); // Key event or focus event will not be received
4699}
4700
arthurhungea3f4fc2020-12-21 23:18:53 +08004701TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4702 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4703
arthurhungea3f4fc2020-12-21 23:18:53 +08004704 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004705 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4706 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004707 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004708
arthurhungea3f4fc2020-12-21 23:18:53 +08004709 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004710 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4711 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004712 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004713
4714 // Add the windows to the dispatcher
4715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4716
4717 PointF pointInFirst = {300, 200};
4718 PointF pointInSecond = {300, 600};
4719
4720 // Send down to the first window
4721 NotifyMotionArgs firstDownMotionArgs =
4722 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4723 ADISPLAY_ID_DEFAULT, {pointInFirst});
4724 mDispatcher->notifyMotion(&firstDownMotionArgs);
4725 // Only the first window should get the down event
4726 firstWindow->consumeMotionDown();
4727 secondWindow->assertNoEvents();
4728
4729 // Send down to the second window
4730 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004731 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004732 {pointInFirst, pointInSecond});
4733 mDispatcher->notifyMotion(&secondDownMotionArgs);
4734 // The first window gets a move and the second a down
4735 firstWindow->consumeMotionMove();
4736 secondWindow->consumeMotionDown();
4737
4738 // Send pointer cancel to the second window
4739 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004740 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004741 {pointInFirst, pointInSecond});
4742 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4743 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4744 // The first window gets move and the second gets cancel.
4745 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4746 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4747
4748 // Send up event.
4749 NotifyMotionArgs upMotionArgs =
4750 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4751 ADISPLAY_ID_DEFAULT);
4752 mDispatcher->notifyMotion(&upMotionArgs);
4753 // The first window gets up and the second gets nothing.
4754 firstWindow->consumeMotionUp();
4755 secondWindow->assertNoEvents();
4756}
4757
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004758TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4759 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4760
4761 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004762 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4764 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4765 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4766 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4767
Harry Cutts33476232023-01-30 19:57:29 +00004768 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004769 window->assertNoEvents();
4770 mDispatcher->waitForIdle();
4771}
4772
chaviwd1c23182019-12-20 18:44:56 -08004773class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004774public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004775 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004776 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004777 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004778 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004779 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004780 }
4781
chaviwd1c23182019-12-20 18:44:56 -08004782 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4783
4784 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4785 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4786 expectedDisplayId, expectedFlags);
4787 }
4788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4790
4791 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4792
chaviwd1c23182019-12-20 18:44:56 -08004793 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4794 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4795 expectedDisplayId, expectedFlags);
4796 }
4797
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004798 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4799 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4800 expectedDisplayId, expectedFlags);
4801 }
4802
chaviwd1c23182019-12-20 18:44:56 -08004803 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4804 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4805 expectedDisplayId, expectedFlags);
4806 }
4807
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004808 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004809 mInputReceiver->consumeMotionEvent(
4810 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4811 WithDisplayId(expectedDisplayId),
4812 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004813 }
4814
Arthur Hungfbfa5722021-11-16 02:45:54 +00004815 void consumeMotionPointerDown(int32_t pointerIdx) {
4816 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4817 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4818 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004819 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004820 }
4821
Evan Rosky84f07f02021-04-16 10:42:42 -07004822 MotionEvent* consumeMotion() {
4823 InputEvent* event = mInputReceiver->consume();
4824 if (!event) {
4825 ADD_FAILURE() << "No event was produced";
4826 return nullptr;
4827 }
4828 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4829 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4830 return nullptr;
4831 }
4832 return static_cast<MotionEvent*>(event);
4833 }
4834
chaviwd1c23182019-12-20 18:44:56 -08004835 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4836
4837private:
4838 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004839};
4840
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004841using InputDispatcherMonitorTest = InputDispatcherTest;
4842
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004843/**
4844 * Two entities that receive touch: A window, and a global monitor.
4845 * The touch goes to the window, and then the window disappears.
4846 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4847 * for the monitor, as well.
4848 * 1. foregroundWindow
4849 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4850 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004851TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004852 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4853 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004854 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004855
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004856 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004857
4858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4860 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4861 {100, 200}))
4862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4863
4864 // Both the foreground window and the global monitor should receive the touch down
4865 window->consumeMotionDown();
4866 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4867
4868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4870 ADISPLAY_ID_DEFAULT, {110, 200}))
4871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4872
4873 window->consumeMotionMove();
4874 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4875
4876 // Now the foreground window goes away
4877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4878 window->consumeMotionCancel();
4879 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4880
4881 // If more events come in, there will be no more foreground window to send them to. This will
4882 // cause a cancel for the monitor, as well.
4883 ASSERT_EQ(InputEventInjectionResult::FAILED,
4884 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4885 ADISPLAY_ID_DEFAULT, {120, 200}))
4886 << "Injection should fail because the window was removed";
4887 window->assertNoEvents();
4888 // Global monitor now gets the cancel
4889 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4890}
4891
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004892TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004893 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004894 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4895 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004897
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004898 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004899
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004903 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004904 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004905}
4906
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004907TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4908 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004909
Chris Yea209fde2020-07-22 13:54:51 -07004910 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004911 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4912 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004918 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004919 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004920
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004921 // Pilfer pointers from the monitor.
4922 // This should not do anything and the window should continue to receive events.
4923 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004926 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4927 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004929
4930 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4931 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004932}
4933
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004934TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004936 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4937 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4939 window->setWindowOffset(20, 40);
4940 window->setWindowTransform(0, 1, -1, 0);
4941
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004942 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004943
4944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4947 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4948 MotionEvent* event = monitor.consumeMotion();
4949 // Even though window has transform, gesture monitor must not.
4950 ASSERT_EQ(ui::Transform(), event->getTransform());
4951}
4952
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004953TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004954 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004955 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004956
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004957 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004958 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004959 << "Injection should fail if there is a monitor, but no touchable window";
4960 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004961}
4962
chaviw81e2bb92019-12-18 15:03:51 -08004963TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004964 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004965 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4966 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004967
Arthur Hung72d8dc32020-03-28 00:48:39 +00004968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004969
4970 NotifyMotionArgs motionArgs =
4971 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4972 ADISPLAY_ID_DEFAULT);
4973
4974 mDispatcher->notifyMotion(&motionArgs);
4975 // Window should receive motion down event.
4976 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4977
4978 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004979 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004980 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4981 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4982 motionArgs.pointerCoords[0].getX() - 10);
4983
4984 mDispatcher->notifyMotion(&motionArgs);
4985 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004986 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004987}
4988
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004989/**
4990 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4991 * the device default right away. In the test scenario, we check both the default value,
4992 * and the action of enabling / disabling.
4993 */
4994TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004996 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4997 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004998 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004999
5000 // Set focused application.
5001 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005002 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005003
5004 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00005005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005006 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00005007 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005008
5009 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07005010 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00005012 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005013
5014 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08005015 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00005016 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005017 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07005018 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005020 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00005021 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005022
5023 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07005024 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00005026 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005027
5028 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08005029 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00005030 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005031 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07005032 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005034 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00005035 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005036
5037 window->assertNoEvents();
5038}
5039
Gang Wange9087892020-01-07 12:17:14 -05005040TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005041 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005042 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5043 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05005044
5045 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005046 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05005047
Arthur Hung72d8dc32020-03-28 00:48:39 +00005048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005049 setFocusedWindow(window);
5050
Harry Cutts33476232023-01-30 19:57:29 +00005051 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05005052
5053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5054 mDispatcher->notifyKey(&keyArgs);
5055
5056 InputEvent* event = window->consume();
5057 ASSERT_NE(event, nullptr);
5058
5059 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5060 ASSERT_NE(verified, nullptr);
5061 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
5062
5063 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
5064 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
5065 ASSERT_EQ(keyArgs.source, verified->source);
5066 ASSERT_EQ(keyArgs.displayId, verified->displayId);
5067
5068 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
5069
5070 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05005071 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005072 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05005073 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
5074 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
5075 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
5076 ASSERT_EQ(0, verifiedKey.repeatCount);
5077}
5078
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005079TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07005080 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005081 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
5082 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005083
5084 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5085
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005086 ui::Transform transform;
5087 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5088
5089 gui::DisplayInfo displayInfo;
5090 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
5091 displayInfo.transform = transform;
5092
5093 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005094
5095 NotifyMotionArgs motionArgs =
5096 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5097 ADISPLAY_ID_DEFAULT);
5098 mDispatcher->notifyMotion(&motionArgs);
5099
5100 InputEvent* event = window->consume();
5101 ASSERT_NE(event, nullptr);
5102
5103 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
5104 ASSERT_NE(verified, nullptr);
5105 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
5106
5107 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
5108 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
5109 EXPECT_EQ(motionArgs.source, verified->source);
5110 EXPECT_EQ(motionArgs.displayId, verified->displayId);
5111
5112 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
5113
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07005114 const vec2 rawXY =
5115 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
5116 motionArgs.pointerCoords[0].getXYValue());
5117 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
5118 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005119 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005120 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005121 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08005122 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
5123 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
5124}
5125
chaviw09c8d2d2020-08-24 15:48:26 -07005126/**
5127 * Ensure that separate calls to sign the same data are generating the same key.
5128 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
5129 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
5130 * tests.
5131 */
5132TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
5133 KeyEvent event = getTestKeyEvent();
5134 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5135
5136 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
5137 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
5138 ASSERT_EQ(hmac1, hmac2);
5139}
5140
5141/**
5142 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
5143 */
5144TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
5145 KeyEvent event = getTestKeyEvent();
5146 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
5147 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
5148
5149 verifiedEvent.deviceId += 1;
5150 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5151
5152 verifiedEvent.source += 1;
5153 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5154
5155 verifiedEvent.eventTimeNanos += 1;
5156 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5157
5158 verifiedEvent.displayId += 1;
5159 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5160
5161 verifiedEvent.action += 1;
5162 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5163
5164 verifiedEvent.downTimeNanos += 1;
5165 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5166
5167 verifiedEvent.flags += 1;
5168 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5169
5170 verifiedEvent.keyCode += 1;
5171 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5172
5173 verifiedEvent.scanCode += 1;
5174 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5175
5176 verifiedEvent.metaState += 1;
5177 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5178
5179 verifiedEvent.repeatCount += 1;
5180 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
5181}
5182
Vishnu Nair958da932020-08-21 17:12:37 -07005183TEST_F(InputDispatcherTest, SetFocusedWindow) {
5184 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5185 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005186 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005187 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005188 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005189 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5190
5191 // Top window is also focusable but is not granted focus.
5192 windowTop->setFocusable(true);
5193 windowSecond->setFocusable(true);
5194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5195 setFocusedWindow(windowSecond);
5196
5197 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5199 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005200
5201 // Focused window should receive event.
5202 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5203 windowTop->assertNoEvents();
5204}
5205
5206TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
5207 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5208 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005209 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005210 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5211
5212 window->setFocusable(true);
5213 // Release channel for window is no longer valid.
5214 window->releaseChannel();
5215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5216 setFocusedWindow(window);
5217
5218 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005219 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5220 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005221
5222 // window channel is invalid, so it should not receive any input event.
5223 window->assertNoEvents();
5224}
5225
5226TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
5227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5228 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005229 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005230 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07005231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5232
Vishnu Nair958da932020-08-21 17:12:37 -07005233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5234 setFocusedWindow(window);
5235
5236 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005237 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5238 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005239
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08005240 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07005241 window->assertNoEvents();
5242}
5243
5244TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
5245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5246 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005247 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005248 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005249 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005250 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5251
5252 windowTop->setFocusable(true);
5253 windowSecond->setFocusable(true);
5254 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5255 setFocusedWindow(windowTop);
5256 windowTop->consumeFocusEvent(true);
5257
5258 setFocusedWindow(windowSecond, windowTop);
5259 windowSecond->consumeFocusEvent(true);
5260 windowTop->consumeFocusEvent(false);
5261
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5263 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005264
5265 // Focused window should receive event.
5266 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
5267}
5268
5269TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
5270 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5271 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005272 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005273 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005274 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005275 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5276
5277 windowTop->setFocusable(true);
5278 windowSecond->setFocusable(true);
5279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
5280 setFocusedWindow(windowSecond, windowTop);
5281
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005282 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5283 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005284
5285 // Event should be dropped.
5286 windowTop->assertNoEvents();
5287 windowSecond->assertNoEvents();
5288}
5289
5290TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
5291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5292 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005293 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005294 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005295 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
5296 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005297 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5298
5299 window->setFocusable(true);
5300 previousFocusedWindow->setFocusable(true);
5301 window->setVisible(false);
5302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
5303 setFocusedWindow(previousFocusedWindow);
5304 previousFocusedWindow->consumeFocusEvent(true);
5305
5306 // Requesting focus on invisible window takes focus from currently focused window.
5307 setFocusedWindow(window);
5308 previousFocusedWindow->consumeFocusEvent(false);
5309
5310 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005312 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5313 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005314
5315 // Window does not get focus event or key down.
5316 window->assertNoEvents();
5317
5318 // Window becomes visible.
5319 window->setVisible(true);
5320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5321
5322 // Window receives focus event.
5323 window->consumeFocusEvent(true);
5324 // Focused window receives key down.
5325 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5326}
5327
Vishnu Nair599f1412021-06-21 10:39:58 -07005328TEST_F(InputDispatcherTest, DisplayRemoved) {
5329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5330 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005331 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07005332 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5333
5334 // window is granted focus.
5335 window->setFocusable(true);
5336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5337 setFocusedWindow(window);
5338 window->consumeFocusEvent(true);
5339
5340 // When a display is removed window loses focus.
5341 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
5342 window->consumeFocusEvent(false);
5343}
5344
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005345/**
5346 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
5347 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
5348 * of the 'slipperyEnterWindow'.
5349 *
5350 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
5351 * a way so that the touched location is no longer covered by the top window.
5352 *
5353 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
5354 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
5355 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
5356 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
5357 * with ACTION_DOWN).
5358 * Thus, the touch has been transferred from the top window into the bottom window, because the top
5359 * window moved itself away from the touched location and had Flag::SLIPPERY.
5360 *
5361 * Even though the top window moved away from the touched location, it is still obscuring the bottom
5362 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
5363 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
5364 *
5365 * In this test, we ensure that the event received by the bottom window has
5366 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
5367 */
5368TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00005369 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
5370 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005371
5372 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5373 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5374
5375 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005376 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005377 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005378 // Make sure this one overlaps the bottom window
5379 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
5380 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
5381 // one. Windows with the same owner are not considered to be occluding each other.
5382 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
5383
5384 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005385 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005386 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
5387
5388 mDispatcher->setInputWindows(
5389 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5390
5391 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
5392 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5393 ADISPLAY_ID_DEFAULT, {{50, 50}});
5394 mDispatcher->notifyMotion(&args);
5395 slipperyExitWindow->consumeMotionDown();
5396 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
5397 mDispatcher->setInputWindows(
5398 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
5399
5400 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5401 ADISPLAY_ID_DEFAULT, {{51, 51}});
5402 mDispatcher->notifyMotion(&args);
5403
5404 slipperyExitWindow->consumeMotionCancel();
5405
5406 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
5407 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5408}
5409
Garfield Tan1c7bc862020-01-28 13:24:04 -08005410class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
5411protected:
5412 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
5413 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
5414
Chris Yea209fde2020-07-22 13:54:51 -07005415 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005416 sp<FakeWindowHandle> mWindow;
5417
5418 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005419 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08005420 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07005421 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005422 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
5423 ASSERT_EQ(OK, mDispatcher->start());
5424
5425 setUpWindow();
5426 }
5427
5428 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07005429 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005430 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005431
Vishnu Nair47074b82020-08-14 11:54:47 -07005432 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005434 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005435 mWindow->consumeFocusEvent(true);
5436 }
5437
Chris Ye2ad95392020-09-01 13:44:44 -07005438 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005439 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005440 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005441 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
5442 mDispatcher->notifyKey(&keyArgs);
5443
5444 // Window should receive key down event.
5445 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5446 }
5447
5448 void expectKeyRepeatOnce(int32_t repeatCount) {
5449 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
5450 InputEvent* repeatEvent = mWindow->consume();
5451 ASSERT_NE(nullptr, repeatEvent);
5452
5453 uint32_t eventType = repeatEvent->getType();
5454 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
5455
5456 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
5457 uint32_t eventAction = repeatKeyEvent->getAction();
5458 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
5459 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
5460 }
5461
Chris Ye2ad95392020-09-01 13:44:44 -07005462 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08005463 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07005464 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08005465 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
5466 mDispatcher->notifyKey(&keyArgs);
5467
5468 // Window should receive key down event.
5469 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00005470 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005471 }
5472};
5473
5474TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00005475 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005476 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5477 expectKeyRepeatOnce(repeatCount);
5478 }
5479}
5480
5481TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00005482 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005483 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5484 expectKeyRepeatOnce(repeatCount);
5485 }
Harry Cutts33476232023-01-30 19:57:29 +00005486 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005487 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08005488 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5489 expectKeyRepeatOnce(repeatCount);
5490 }
5491}
5492
5493TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005494 sendAndConsumeKeyDown(/*deviceId=*/1);
5495 expectKeyRepeatOnce(/*repeatCount=*/1);
5496 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005497 mWindow->assertNoEvents();
5498}
5499
5500TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005501 sendAndConsumeKeyDown(/*deviceId=*/1);
5502 expectKeyRepeatOnce(/*repeatCount=*/1);
5503 sendAndConsumeKeyDown(/*deviceId=*/2);
5504 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005505 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00005506 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005507 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00005508 expectKeyRepeatOnce(/*repeatCount=*/2);
5509 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07005510 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00005511 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005512 mWindow->assertNoEvents();
5513}
5514
5515TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00005516 sendAndConsumeKeyDown(/*deviceId=*/1);
5517 expectKeyRepeatOnce(/*repeatCount=*/1);
5518 sendAndConsumeKeyDown(/*deviceId=*/2);
5519 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07005520 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00005521 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07005522 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08005523 mWindow->assertNoEvents();
5524}
5525
liushenxiang42232912021-05-21 20:24:09 +08005526TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
5527 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00005528 expectKeyRepeatOnce(/*repeatCount=*/1);
5529 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08005530 mDispatcher->notifyDeviceReset(&args);
5531 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
5532 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
5533 mWindow->assertNoEvents();
5534}
5535
Garfield Tan1c7bc862020-01-28 13:24:04 -08005536TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005537 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005538 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005539 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5540 InputEvent* repeatEvent = mWindow->consume();
5541 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5542 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
5543 IdGenerator::getSource(repeatEvent->getId()));
5544 }
5545}
5546
5547TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00005548 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00005549 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08005550
5551 std::unordered_set<int32_t> idSet;
5552 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
5553 InputEvent* repeatEvent = mWindow->consume();
5554 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
5555 int32_t id = repeatEvent->getId();
5556 EXPECT_EQ(idSet.end(), idSet.find(id));
5557 idSet.insert(id);
5558 }
5559}
5560
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005561/* Test InputDispatcher for MultiDisplay */
5562class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
5563public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005564 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005565 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08005566
Chris Yea209fde2020-07-22 13:54:51 -07005567 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005568 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005569 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005570
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005571 // Set focus window for primary display, but focused display would be second one.
5572 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07005573 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005575 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005576 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08005577
Chris Yea209fde2020-07-22 13:54:51 -07005578 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005579 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005580 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005581 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005582 // Set focus display to second one.
5583 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
5584 // Set focus window for second display.
5585 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07005586 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005587 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005588 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005589 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005590 }
5591
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005592 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005593 InputDispatcherTest::TearDown();
5594
Chris Yea209fde2020-07-22 13:54:51 -07005595 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005596 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07005597 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005598 windowInSecondary.clear();
5599 }
5600
5601protected:
Chris Yea209fde2020-07-22 13:54:51 -07005602 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005603 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07005604 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005605 sp<FakeWindowHandle> windowInSecondary;
5606};
5607
5608TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
5609 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005613 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08005614 windowInSecondary->assertNoEvents();
5615
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005616 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005620 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005621 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08005622}
5623
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005624TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005625 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5627 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005628 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005629 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08005630 windowInSecondary->assertNoEvents();
5631
5632 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005634 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005635 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005636 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005637
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005638 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005639 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005640
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005641 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005642 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5643 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005644
5645 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005646 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005647 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005648 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005649 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005650 windowInSecondary->assertNoEvents();
5651}
5652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005653// Test per-display input monitors for motion event.
5654TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005655 FakeMonitorReceiver monitorInPrimary =
5656 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5657 FakeMonitorReceiver monitorInSecondary =
5658 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005659
5660 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005664 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005665 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005666 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005667 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005668
5669 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005673 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005674 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005675 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005676 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005677
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -08005678 // Lift up the touch from the second display
5679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5680 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5682 windowInSecondary->consumeMotionUp(SECOND_DISPLAY_ID);
5683 monitorInSecondary.consumeMotionUp(SECOND_DISPLAY_ID);
5684
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005685 // Test inject a non-pointer motion event.
5686 // If specific a display, it will dispatch to the focused window of particular display,
5687 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5689 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005691 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005692 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005693 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005694 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005695}
5696
5697// Test per-display input monitors for key event.
5698TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005699 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005700 FakeMonitorReceiver monitorInPrimary =
5701 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5702 FakeMonitorReceiver monitorInSecondary =
5703 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005704
5705 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5707 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005708 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005709 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005710 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005711 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005712}
5713
Vishnu Nair958da932020-08-21 17:12:37 -07005714TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5715 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005716 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005717 secondWindowInPrimary->setFocusable(true);
5718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5719 setFocusedWindow(secondWindowInPrimary);
5720 windowInPrimary->consumeFocusEvent(false);
5721 secondWindowInPrimary->consumeFocusEvent(true);
5722
5723 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5725 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005726 windowInPrimary->assertNoEvents();
5727 windowInSecondary->assertNoEvents();
5728 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5729}
5730
Arthur Hungdfd528e2021-12-08 13:23:04 +00005731TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5732 FakeMonitorReceiver monitorInPrimary =
5733 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5734 FakeMonitorReceiver monitorInSecondary =
5735 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5736
5737 // Test touch down on primary display.
5738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5739 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5740 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5741 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5742 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5743
5744 // Test touch down on second display.
5745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5746 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5747 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5748 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5749 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5750
5751 // Trigger cancel touch.
5752 mDispatcher->cancelCurrentTouch();
5753 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5754 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5755 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5756 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5757
5758 // Test inject a move motion event, no window/monitor should receive the event.
5759 ASSERT_EQ(InputEventInjectionResult::FAILED,
5760 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5761 ADISPLAY_ID_DEFAULT, {110, 200}))
5762 << "Inject motion event should return InputEventInjectionResult::FAILED";
5763 windowInPrimary->assertNoEvents();
5764 monitorInPrimary.assertNoEvents();
5765
5766 ASSERT_EQ(InputEventInjectionResult::FAILED,
5767 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5768 SECOND_DISPLAY_ID, {110, 200}))
5769 << "Inject motion event should return InputEventInjectionResult::FAILED";
5770 windowInSecondary->assertNoEvents();
5771 monitorInSecondary.assertNoEvents();
5772}
5773
Jackal Guof9696682018-10-05 12:23:23 +08005774class InputFilterTest : public InputDispatcherTest {
5775protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005776 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5777 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005778 NotifyMotionArgs motionArgs;
5779
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005780 motionArgs =
5781 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005782 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005783 motionArgs =
5784 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005785 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005786 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005787 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005788 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5789 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005790 } else {
5791 mFakePolicy->assertFilterInputEventWasNotCalled();
5792 }
5793 }
5794
5795 void testNotifyKey(bool expectToBeFiltered) {
5796 NotifyKeyArgs keyArgs;
5797
5798 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5799 mDispatcher->notifyKey(&keyArgs);
5800 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5801 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005802 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005803
5804 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005805 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005806 } else {
5807 mFakePolicy->assertFilterInputEventWasNotCalled();
5808 }
5809 }
5810};
5811
5812// Test InputFilter for MotionEvent
5813TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5814 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5815 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5816 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5817
5818 // Enable InputFilter
5819 mDispatcher->setInputFilterEnabled(true);
5820 // Test touch on both primary and second display, and check if both events are filtered.
5821 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5822 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5823
5824 // Disable InputFilter
5825 mDispatcher->setInputFilterEnabled(false);
5826 // Test touch on both primary and second display, and check if both events aren't filtered.
5827 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5828 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5829}
5830
5831// Test InputFilter for KeyEvent
5832TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5833 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5834 testNotifyKey(/*expectToBeFiltered*/ false);
5835
5836 // Enable InputFilter
5837 mDispatcher->setInputFilterEnabled(true);
5838 // Send a key event, and check if it is filtered.
5839 testNotifyKey(/*expectToBeFiltered*/ true);
5840
5841 // Disable InputFilter
5842 mDispatcher->setInputFilterEnabled(false);
5843 // Send a key event, and check if it isn't filtered.
5844 testNotifyKey(/*expectToBeFiltered*/ false);
5845}
5846
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005847// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5848// logical display coordinate space.
5849TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5850 ui::Transform firstDisplayTransform;
5851 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5852 ui::Transform secondDisplayTransform;
5853 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5854
5855 std::vector<gui::DisplayInfo> displayInfos(2);
5856 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5857 displayInfos[0].transform = firstDisplayTransform;
5858 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5859 displayInfos[1].transform = secondDisplayTransform;
5860
5861 mDispatcher->onWindowInfosChanged({}, displayInfos);
5862
5863 // Enable InputFilter
5864 mDispatcher->setInputFilterEnabled(true);
5865
5866 // Ensure the correct transforms are used for the displays.
5867 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5868 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5869}
5870
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005871class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5872protected:
5873 virtual void SetUp() override {
5874 InputDispatcherTest::SetUp();
5875
5876 /**
5877 * We don't need to enable input filter to test the injected event policy, but we enabled it
5878 * here to make the tests more realistic, since this policy only matters when inputfilter is
5879 * on.
5880 */
5881 mDispatcher->setInputFilterEnabled(true);
5882
5883 std::shared_ptr<InputApplicationHandle> application =
5884 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005885 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5886 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005887
5888 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5889 mWindow->setFocusable(true);
5890 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5891 setFocusedWindow(mWindow);
5892 mWindow->consumeFocusEvent(true);
5893 }
5894
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005895 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5896 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005897 KeyEvent event;
5898
5899 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5900 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5901 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005902 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005903 const int32_t additionalPolicyFlags =
5904 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005906 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005907 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5908 policyFlags | additionalPolicyFlags));
5909
5910 InputEvent* received = mWindow->consume();
5911 ASSERT_NE(nullptr, received);
5912 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005913 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5914 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5915 ASSERT_EQ(flags, keyEvent.getFlags());
5916 }
5917
5918 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5919 int32_t flags) {
5920 MotionEvent event;
5921 PointerProperties pointerProperties[1];
5922 PointerCoords pointerCoords[1];
5923 pointerProperties[0].clear();
5924 pointerProperties[0].id = 0;
5925 pointerCoords[0].clear();
5926 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5927 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5928
5929 ui::Transform identityTransform;
5930 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5931 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5932 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5933 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5934 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005935 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005936 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005937 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5938
5939 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005941 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005942 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5943 policyFlags | additionalPolicyFlags));
5944
5945 InputEvent* received = mWindow->consume();
5946 ASSERT_NE(nullptr, received);
5947 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5948 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5949 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5950 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005951 }
5952
5953private:
5954 sp<FakeWindowHandle> mWindow;
5955};
5956
5957TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005958 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5959 // filter. Without it, the event will no different from a regularly injected event, and the
5960 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005961 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5962 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005963}
5964
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005965TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005966 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005967 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005968 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5969}
5970
5971TEST_F(InputFilterInjectionPolicyTest,
5972 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5973 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005974 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005975 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005976}
5977
5978TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005979 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5980 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005981}
5982
chaviwfd6d3512019-03-25 13:23:49 -07005983class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005984 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005985 InputDispatcherTest::SetUp();
5986
Chris Yea209fde2020-07-22 13:54:51 -07005987 std::shared_ptr<FakeApplicationHandle> application =
5988 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005989 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005990 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005991 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005992
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005993 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005994 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005995 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005996
5997 // Set focused application.
5998 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005999 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07006000
6001 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00006002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006003 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01006004 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07006005 }
6006
Prabir Pradhan3608aad2019-10-02 17:08:26 -07006007 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07006008 InputDispatcherTest::TearDown();
6009
6010 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08006011 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07006012 }
6013
6014protected:
6015 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08006016 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006017 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07006018};
6019
6020// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
6021// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
6022// the onPointerDownOutsideFocus callback.
6023TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006025 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6026 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006027 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006028 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006029
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006030 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07006031 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
6032}
6033
6034// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
6035// DOWN on the window that doesn't have focus. Ensure no window received the
6036// onPointerDownOutsideFocus callback.
6037TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006039 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006040 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006041 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006042
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006043 ASSERT_TRUE(mDispatcher->waitForIdle());
6044 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006045}
6046
6047// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
6048// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
6049TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6051 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006052 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006053 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07006054
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006055 ASSERT_TRUE(mDispatcher->waitForIdle());
6056 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006057}
6058
6059// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
6060// DOWN on the window that already has focus. Ensure no window received the
6061// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10006062TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08006064 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07006065 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006066 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07006067 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07006068
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006069 ASSERT_TRUE(mDispatcher->waitForIdle());
6070 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07006071}
6072
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08006073// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
6074// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
6075TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
6076 const MotionEvent event =
6077 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6078 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00006079 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08006080 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
6081 .build();
6082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
6083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6084 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
6085
6086 ASSERT_TRUE(mDispatcher->waitForIdle());
6087 mFakePolicy->assertOnPointerDownWasNotCalled();
6088 // Ensure that the unfocused window did not receive any FOCUS events.
6089 mUnfocusedWindow->assertNoEvents();
6090}
6091
chaviwaf87b3e2019-10-01 16:59:28 -07006092// These tests ensures we can send touch events to a single client when there are multiple input
6093// windows that point to the same client token.
6094class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
6095 virtual void SetUp() override {
6096 InputDispatcherTest::SetUp();
6097
Chris Yea209fde2020-07-22 13:54:51 -07006098 std::shared_ptr<FakeApplicationHandle> application =
6099 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006100 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
6101 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07006102 mWindow1->setFrame(Rect(0, 0, 100, 100));
6103
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006104 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
6105 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07006106 mWindow2->setFrame(Rect(100, 100, 200, 200));
6107
Arthur Hung72d8dc32020-03-28 00:48:39 +00006108 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07006109 }
6110
6111protected:
6112 sp<FakeWindowHandle> mWindow1;
6113 sp<FakeWindowHandle> mWindow2;
6114
6115 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05006116 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07006117 vec2 vals = windowInfo->transform.transform(point.x, point.y);
6118 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07006119 }
6120
6121 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
6122 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01006123 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07006124 InputEvent* event = window->consume();
6125
6126 ASSERT_NE(nullptr, event) << name.c_str()
6127 << ": consumer should have returned non-NULL event.";
6128
6129 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
6130 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
6131 << " event, got " << inputEventTypeToString(event->getType()) << " event";
6132
6133 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00006134 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08006135 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07006136
6137 for (size_t i = 0; i < points.size(); i++) {
6138 float expectedX = points[i].x;
6139 float expectedY = points[i].y;
6140
6141 EXPECT_EQ(expectedX, motionEvent.getX(i))
6142 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
6143 << ", got " << motionEvent.getX(i);
6144 EXPECT_EQ(expectedY, motionEvent.getY(i))
6145 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
6146 << ", got " << motionEvent.getY(i);
6147 }
6148 }
chaviw9eaa22c2020-07-01 16:21:27 -07006149
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08006150 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07006151 std::vector<PointF> expectedPoints) {
6152 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
6153 ADISPLAY_ID_DEFAULT, touchedPoints);
6154 mDispatcher->notifyMotion(&motionArgs);
6155
6156 // Always consume from window1 since it's the window that has the InputReceiver
6157 consumeMotionEvent(mWindow1, action, expectedPoints);
6158 }
chaviwaf87b3e2019-10-01 16:59:28 -07006159};
6160
6161TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
6162 // Touch Window 1
6163 PointF touchedPoint = {10, 10};
6164 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006165 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006166
6167 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006168 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006169
6170 // Touch Window 2
6171 touchedPoint = {150, 150};
6172 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006173 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006174}
6175
chaviw9eaa22c2020-07-01 16:21:27 -07006176TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
6177 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07006178 mWindow2->setWindowScale(0.5f, 0.5f);
6179
6180 // Touch Window 1
6181 PointF touchedPoint = {10, 10};
6182 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006183 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006184 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07006185 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006186
6187 // Touch Window 2
6188 touchedPoint = {150, 150};
6189 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07006190 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
6191 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006192
chaviw9eaa22c2020-07-01 16:21:27 -07006193 // Update the transform so rotation is set
6194 mWindow2->setWindowTransform(0, -1, 1, 0);
6195 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
6196 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07006197}
6198
chaviw9eaa22c2020-07-01 16:21:27 -07006199TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006200 mWindow2->setWindowScale(0.5f, 0.5f);
6201
6202 // Touch Window 1
6203 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6204 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006205 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006206
6207 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006208 touchedPoints.push_back(PointF{150, 150});
6209 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006210 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006211
chaviw9eaa22c2020-07-01 16:21:27 -07006212 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006213 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006214 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006215
chaviw9eaa22c2020-07-01 16:21:27 -07006216 // Update the transform so rotation is set for Window 2
6217 mWindow2->setWindowTransform(0, -1, 1, 0);
6218 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006219 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006220}
6221
chaviw9eaa22c2020-07-01 16:21:27 -07006222TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006223 mWindow2->setWindowScale(0.5f, 0.5f);
6224
6225 // Touch Window 1
6226 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6227 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006228 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006229
6230 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006231 touchedPoints.push_back(PointF{150, 150});
6232 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006233
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006234 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006235
6236 // Move both windows
6237 touchedPoints = {{20, 20}, {175, 175}};
6238 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6239 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6240
chaviw9eaa22c2020-07-01 16:21:27 -07006241 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006242
chaviw9eaa22c2020-07-01 16:21:27 -07006243 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006244 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006245 expectedPoints.pop_back();
6246
6247 // Touch Window 2
6248 mWindow2->setWindowTransform(0, -1, 1, 0);
6249 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006250 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07006251
6252 // Move both windows
6253 touchedPoints = {{20, 20}, {175, 175}};
6254 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6255 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6256
6257 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006258}
6259
6260TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
6261 mWindow1->setWindowScale(0.5f, 0.5f);
6262
6263 // Touch Window 1
6264 std::vector<PointF> touchedPoints = {PointF{10, 10}};
6265 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07006266 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006267
6268 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07006269 touchedPoints.push_back(PointF{150, 150});
6270 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006271
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006272 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006273
6274 // Move both windows
6275 touchedPoints = {{20, 20}, {175, 175}};
6276 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
6277 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
6278
chaviw9eaa22c2020-07-01 16:21:27 -07006279 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00006280}
6281
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006282class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
6283 virtual void SetUp() override {
6284 InputDispatcherTest::SetUp();
6285
Chris Yea209fde2020-07-22 13:54:51 -07006286 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006287 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006288 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
6289 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006290 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006291 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07006292 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006293
6294 // Set focused application.
6295 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
6296
6297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006298 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006299 mWindow->consumeFocusEvent(true);
6300 }
6301
6302 virtual void TearDown() override {
6303 InputDispatcherTest::TearDown();
6304 mWindow.clear();
6305 }
6306
6307protected:
Chris Yea209fde2020-07-22 13:54:51 -07006308 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006309 sp<FakeWindowHandle> mWindow;
6310 static constexpr PointF WINDOW_LOCATION = {20, 20};
6311
6312 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006314 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6315 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006317 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6318 WINDOW_LOCATION));
6319 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006320
6321 sp<FakeWindowHandle> addSpyWindow() {
6322 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006323 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006324 spy->setTrustedOverlay(true);
6325 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006326 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006327 spy->setDispatchingTimeout(30ms);
6328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
6329 return spy;
6330 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006331};
6332
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006333// Send a tap and respond, which should not cause an ANR.
6334TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
6335 tapOnWindow();
6336 mWindow->consumeMotionDown();
6337 mWindow->consumeMotionUp();
6338 ASSERT_TRUE(mDispatcher->waitForIdle());
6339 mFakePolicy->assertNotifyAnrWasNotCalled();
6340}
6341
6342// Send a regular key and respond, which should not cause an ANR.
6343TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006345 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6346 ASSERT_TRUE(mDispatcher->waitForIdle());
6347 mFakePolicy->assertNotifyAnrWasNotCalled();
6348}
6349
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006350TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
6351 mWindow->setFocusable(false);
6352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6353 mWindow->consumeFocusEvent(false);
6354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006355 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006356 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6357 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6358 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05006360 // Key will not go to window because we have no focused window.
6361 // The 'no focused window' ANR timer should start instead.
6362
6363 // Now, the focused application goes away.
6364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
6365 // The key should get dropped and there should be no ANR.
6366
6367 ASSERT_TRUE(mDispatcher->waitForIdle());
6368 mFakePolicy->assertNotifyAnrWasNotCalled();
6369}
6370
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006371// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006372// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
6373// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006374TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006376 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6377 WINDOW_LOCATION));
6378
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006379 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
6380 ASSERT_TRUE(sequenceNum);
6381 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006382 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006384 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006385 mWindow->consumeMotionEvent(
6386 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006387 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006388 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006389}
6390
6391// Send a key to the app and have the app not respond right away.
6392TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
6393 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08006394 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006395 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
6396 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006397 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006398 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006399 ASSERT_TRUE(mDispatcher->waitForIdle());
6400}
6401
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006402// We have a focused application, but no focused window
6403TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006404 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6406 mWindow->consumeFocusEvent(false);
6407
6408 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006410 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6411 WINDOW_LOCATION));
6412 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
6413 mDispatcher->waitForIdle();
6414 mFakePolicy->assertNotifyAnrWasNotCalled();
6415
6416 // Once a focused event arrives, we get an ANR for this application
6417 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6418 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006419 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006420 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6421 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006422 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006423 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07006424 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006425 ASSERT_TRUE(mDispatcher->waitForIdle());
6426}
6427
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006428/**
6429 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
6430 * there will not be an ANR.
6431 */
6432TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
6433 mWindow->setFocusable(false);
6434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6435 mWindow->consumeFocusEvent(false);
6436
6437 KeyEvent event;
6438 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
6439 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
6440
6441 // Define a valid key down event that is stale (too old).
6442 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
6443 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00006444 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006445
6446 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
6447
6448 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006449 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08006450 InputEventInjectionSync::WAIT_FOR_RESULT,
6451 INJECT_EVENT_TIMEOUT, policyFlags);
6452 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
6453 << "Injection should fail because the event is stale";
6454
6455 ASSERT_TRUE(mDispatcher->waitForIdle());
6456 mFakePolicy->assertNotifyAnrWasNotCalled();
6457 mWindow->assertNoEvents();
6458}
6459
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006460// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006461// Make sure that we don't notify policy twice about the same ANR.
6462TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006463 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006464 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6465 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006466
6467 // Once a focused event arrives, we get an ANR for this application
6468 // We specify the injection timeout to be smaller than the application timeout, to ensure that
6469 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006470 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006471 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6472 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006473 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07006474 const std::chrono::duration appTimeout =
6475 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6476 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006477
Vishnu Naire4df8752022-09-08 09:17:55 -07006478 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006479 // ANR should not be raised again. It is up to policy to do that if it desires.
6480 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006481
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006482 // If we now get a focused window, the ANR should stop, but the policy handles that via
6483 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006484 ASSERT_TRUE(mDispatcher->waitForIdle());
6485}
6486
6487// We have a focused application, but no focused window
6488TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07006489 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6491 mWindow->consumeFocusEvent(false);
6492
6493 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006494 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006495 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006496 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6497 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006498
Vishnu Naire4df8752022-09-08 09:17:55 -07006499 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
6500 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006501
6502 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006503 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006504 ASSERT_TRUE(mDispatcher->waitForIdle());
6505 mWindow->assertNoEvents();
6506}
6507
6508/**
6509 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
6510 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
6511 * If we process 1 of the events, but ANR on the second event with the same timestamp,
6512 * the ANR mechanism should still work.
6513 *
6514 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
6515 * DOWN event, while not responding on the second one.
6516 */
6517TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
6518 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
6519 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6520 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6521 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6522 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006523 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006524
6525 // Now send ACTION_UP, with identical timestamp
6526 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
6527 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
6528 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
6529 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006530 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006531
6532 // We have now sent down and up. Let's consume first event and then ANR on the second.
6533 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6534 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006535 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006536}
6537
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006538// A spy window can receive an ANR
6539TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
6540 sp<FakeWindowHandle> spy = addSpyWindow();
6541
6542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6543 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6544 WINDOW_LOCATION));
6545 mWindow->consumeMotionDown();
6546
6547 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
6548 ASSERT_TRUE(sequenceNum);
6549 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006550 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006551
6552 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006553 spy->consumeMotionEvent(
6554 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006555 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006556 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006557}
6558
6559// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006560// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006561TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
6562 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006563
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6565 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006566 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006568
6569 // Stuck on the ACTION_UP
6570 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006571 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006572
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006573 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006574 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006575 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6576 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006577
6578 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6579 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006580 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006581 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006582 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006583}
6584
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006585// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006586// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006587TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
6588 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006589
6590 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006591 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6592 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006593
6594 mWindow->consumeMotionDown();
6595 // Stuck on the ACTION_UP
6596 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006597 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006598
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006599 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006600 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006601 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6602 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006603
6604 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
6605 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006606 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006607 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006608 spy->assertNoEvents();
6609}
6610
6611TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
6612 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
6613
6614 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
6615
6616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6618 WINDOW_LOCATION));
6619
6620 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6621 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
6622 ASSERT_TRUE(consumeSeq);
6623
Prabir Pradhanedd96402022-02-15 01:46:16 -08006624 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006625
6626 monitor.finishEvent(*consumeSeq);
6627 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
6628
6629 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006630 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006631}
6632
6633// If a window is unresponsive, then you get anr. if the window later catches up and starts to
6634// process events, you don't get an anr. When the window later becomes unresponsive again, you
6635// get an ANR again.
6636// 1. tap -> block on ACTION_UP -> receive ANR
6637// 2. consume all pending events (= queue becomes healthy again)
6638// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6639TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6640 tapOnWindow();
6641
6642 mWindow->consumeMotionDown();
6643 // Block on ACTION_UP
6644 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006645 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006646 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6647 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006648 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006649 mWindow->assertNoEvents();
6650
6651 tapOnWindow();
6652 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006653 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006654 mWindow->consumeMotionUp();
6655
6656 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006657 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006658 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006659 mWindow->assertNoEvents();
6660}
6661
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006662// If a connection remains unresponsive for a while, make sure policy is only notified once about
6663// it.
6664TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006666 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6667 WINDOW_LOCATION));
6668
6669 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006670 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006671 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006672 // 'notifyConnectionUnresponsive' should only be called once per connection
6673 mFakePolicy->assertNotifyAnrWasNotCalled();
6674 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006675 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006676 mWindow->consumeMotionEvent(
6677 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006678 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006679 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006680 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006681 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006682}
6683
6684/**
6685 * If a window is processing a motion event, and then a key event comes in, the key event should
6686 * not to to the focused window until the motion is processed.
6687 *
6688 * Warning!!!
6689 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6690 * and the injection timeout that we specify when injecting the key.
6691 * We must have the injection timeout (10ms) be smaller than
6692 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6693 *
6694 * If that value changes, this test should also change.
6695 */
6696TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6697 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6699
6700 tapOnWindow();
6701 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6702 ASSERT_TRUE(downSequenceNum);
6703 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6704 ASSERT_TRUE(upSequenceNum);
6705 // Don't finish the events yet, and send a key
6706 // Injection will "succeed" because we will eventually give up and send the key to the focused
6707 // window even if motions are still being processed. But because the injection timeout is short,
6708 // we will receive INJECTION_TIMED_OUT as the result.
6709
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006710 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006711 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006712 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6713 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006714 // Key will not be sent to the window, yet, because the window is still processing events
6715 // and the key remains pending, waiting for the touch events to be processed
6716 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6717 ASSERT_FALSE(keySequenceNum);
6718
6719 std::this_thread::sleep_for(500ms);
6720 // if we wait long enough though, dispatcher will give up, and still send the key
6721 // to the focused window, even though we have not yet finished the motion event
6722 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6723 mWindow->finishEvent(*downSequenceNum);
6724 mWindow->finishEvent(*upSequenceNum);
6725}
6726
6727/**
6728 * If a window is processing a motion event, and then a key event comes in, the key event should
6729 * not go to the focused window until the motion is processed.
6730 * If then a new motion comes in, then the pending key event should be going to the currently
6731 * focused window right away.
6732 */
6733TEST_F(InputDispatcherSingleWindowAnr,
6734 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6735 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6737
6738 tapOnWindow();
6739 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6740 ASSERT_TRUE(downSequenceNum);
6741 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6742 ASSERT_TRUE(upSequenceNum);
6743 // Don't finish the events yet, and send a key
6744 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006746 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6747 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006748 // At this point, key is still pending, and should not be sent to the application yet.
6749 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6750 ASSERT_FALSE(keySequenceNum);
6751
6752 // Now tap down again. It should cause the pending key to go to the focused window right away.
6753 tapOnWindow();
6754 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6755 // the other events yet. We can finish events in any order.
6756 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6757 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6758 mWindow->consumeMotionDown();
6759 mWindow->consumeMotionUp();
6760 mWindow->assertNoEvents();
6761}
6762
6763class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6764 virtual void SetUp() override {
6765 InputDispatcherTest::SetUp();
6766
Chris Yea209fde2020-07-22 13:54:51 -07006767 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006768 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006769 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6770 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006771 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006772 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006773 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006774
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006775 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6776 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006777 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006778 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006779
6780 // Set focused application.
6781 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006782 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006783
6784 // Expect one focus window exist in display.
6785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006786 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006787 mFocusedWindow->consumeFocusEvent(true);
6788 }
6789
6790 virtual void TearDown() override {
6791 InputDispatcherTest::TearDown();
6792
6793 mUnfocusedWindow.clear();
6794 mFocusedWindow.clear();
6795 }
6796
6797protected:
Chris Yea209fde2020-07-22 13:54:51 -07006798 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006799 sp<FakeWindowHandle> mUnfocusedWindow;
6800 sp<FakeWindowHandle> mFocusedWindow;
6801 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6802 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6803 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6804
6805 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6806
6807 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6808
6809private:
6810 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6813 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006815 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6816 location));
6817 }
6818};
6819
6820// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6821// should be ANR'd first.
6822TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6825 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006827 mFocusedWindow->consumeMotionDown();
6828 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006829 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006830 // We consumed all events, so no ANR
6831 ASSERT_TRUE(mDispatcher->waitForIdle());
6832 mFakePolicy->assertNotifyAnrWasNotCalled();
6833
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006835 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6836 FOCUSED_WINDOW_LOCATION));
6837 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6838 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006839
6840 const std::chrono::duration timeout =
6841 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006842 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006843 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6844 // sequence to make it consistent
6845 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006846 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006847 mFocusedWindow->consumeMotionDown();
6848 // This cancel is generated because the connection was unresponsive
6849 mFocusedWindow->consumeMotionCancel();
6850 mFocusedWindow->assertNoEvents();
6851 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006852 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006853 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6854 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006855 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006856}
6857
6858// If we have 2 windows with identical timeouts that are both unresponsive,
6859// it doesn't matter which order they should have ANR.
6860// But we should receive ANR for both.
6861TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6862 // Set the timeout for unfocused window to match the focused window
6863 mUnfocusedWindow->setDispatchingTimeout(10ms);
6864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6865
6866 tapOnFocusedWindow();
6867 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006868 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6869 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6870 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006871
6872 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006873 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6874 mFocusedWindow->getToken() == anrConnectionToken2);
6875 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6876 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006877
6878 ASSERT_TRUE(mDispatcher->waitForIdle());
6879 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006880
6881 mFocusedWindow->consumeMotionDown();
6882 mFocusedWindow->consumeMotionUp();
6883 mUnfocusedWindow->consumeMotionOutside();
6884
Prabir Pradhanedd96402022-02-15 01:46:16 -08006885 sp<IBinder> responsiveToken1, responsiveToken2;
6886 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6887 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006888
6889 // Both applications should be marked as responsive, in any order
6890 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6891 mFocusedWindow->getToken() == responsiveToken2);
6892 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6893 mUnfocusedWindow->getToken() == responsiveToken2);
6894 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006895}
6896
6897// If a window is already not responding, the second tap on the same window should be ignored.
6898// We should also log an error to account for the dropped event (not tested here).
6899// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6900TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6901 tapOnFocusedWindow();
6902 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006903 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006904 // Receive the events, but don't respond
6905 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6906 ASSERT_TRUE(downEventSequenceNum);
6907 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6908 ASSERT_TRUE(upEventSequenceNum);
6909 const std::chrono::duration timeout =
6910 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006911 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006912
6913 // Tap once again
6914 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006915 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6917 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006918 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006919 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6920 FOCUSED_WINDOW_LOCATION));
6921 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6922 // valid touch target
6923 mUnfocusedWindow->assertNoEvents();
6924
6925 // Consume the first tap
6926 mFocusedWindow->finishEvent(*downEventSequenceNum);
6927 mFocusedWindow->finishEvent(*upEventSequenceNum);
6928 ASSERT_TRUE(mDispatcher->waitForIdle());
6929 // The second tap did not go to the focused window
6930 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006931 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006932 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6933 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006934 mFakePolicy->assertNotifyAnrWasNotCalled();
6935}
6936
6937// If you tap outside of all windows, there will not be ANR
6938TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006939 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006940 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6941 LOCATION_OUTSIDE_ALL_WINDOWS));
6942 ASSERT_TRUE(mDispatcher->waitForIdle());
6943 mFakePolicy->assertNotifyAnrWasNotCalled();
6944}
6945
6946// Since the focused window is paused, tapping on it should not produce any events
6947TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6948 mFocusedWindow->setPaused(true);
6949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6950
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006951 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6953 FOCUSED_WINDOW_LOCATION));
6954
6955 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6956 ASSERT_TRUE(mDispatcher->waitForIdle());
6957 // Should not ANR because the window is paused, and touches shouldn't go to it
6958 mFakePolicy->assertNotifyAnrWasNotCalled();
6959
6960 mFocusedWindow->assertNoEvents();
6961 mUnfocusedWindow->assertNoEvents();
6962}
6963
6964/**
6965 * If a window is processing a motion event, and then a key event comes in, the key event should
6966 * not to to the focused window until the motion is processed.
6967 * If a different window becomes focused at this time, the key should go to that window instead.
6968 *
6969 * Warning!!!
6970 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6971 * and the injection timeout that we specify when injecting the key.
6972 * We must have the injection timeout (10ms) be smaller than
6973 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6974 *
6975 * If that value changes, this test should also change.
6976 */
6977TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6978 // Set a long ANR timeout to prevent it from triggering
6979 mFocusedWindow->setDispatchingTimeout(2s);
6980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6981
6982 tapOnUnfocusedWindow();
6983 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6984 ASSERT_TRUE(downSequenceNum);
6985 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6986 ASSERT_TRUE(upSequenceNum);
6987 // Don't finish the events yet, and send a key
6988 // Injection will succeed because we will eventually give up and send the key to the focused
6989 // window even if motions are still being processed.
6990
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006991 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006992 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6993 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006995 // Key will not be sent to the window, yet, because the window is still processing events
6996 // and the key remains pending, waiting for the touch events to be processed
6997 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6998 ASSERT_FALSE(keySequenceNum);
6999
7000 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07007001 mFocusedWindow->setFocusable(false);
7002 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007003 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07007004 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007005
7006 // Focus events should precede the key events
7007 mUnfocusedWindow->consumeFocusEvent(true);
7008 mFocusedWindow->consumeFocusEvent(false);
7009
7010 // Finish the tap events, which should unblock dispatcher
7011 mUnfocusedWindow->finishEvent(*downSequenceNum);
7012 mUnfocusedWindow->finishEvent(*upSequenceNum);
7013
7014 // Now that all queues are cleared and no backlog in the connections, the key event
7015 // can finally go to the newly focused "mUnfocusedWindow".
7016 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7017 mFocusedWindow->assertNoEvents();
7018 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05007019 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007020}
7021
7022// When the touch stream is split across 2 windows, and one of them does not respond,
7023// then ANR should be raised and the touch should be canceled for the unresponsive window.
7024// The other window should not be affected by that.
7025TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
7026 // Touch Window 1
7027 NotifyMotionArgs motionArgs =
7028 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7029 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
7030 mDispatcher->notifyMotion(&motionArgs);
7031 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00007032 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007033
7034 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007035 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7036 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007037 mDispatcher->notifyMotion(&motionArgs);
7038
7039 const std::chrono::duration timeout =
7040 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08007041 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007042
7043 mUnfocusedWindow->consumeMotionDown();
7044 mFocusedWindow->consumeMotionDown();
7045 // Focused window may or may not receive ACTION_MOVE
7046 // But it should definitely receive ACTION_CANCEL due to the ANR
7047 InputEvent* event;
7048 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
7049 ASSERT_TRUE(moveOrCancelSequenceNum);
7050 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
7051 ASSERT_NE(nullptr, event);
7052 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
7053 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
7054 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
7055 mFocusedWindow->consumeMotionCancel();
7056 } else {
7057 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
7058 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007059 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08007060 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
7061 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05007062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007063 mUnfocusedWindow->assertNoEvents();
7064 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05007065 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07007066}
7067
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007068/**
7069 * If we have no focused window, and a key comes in, we start the ANR timer.
7070 * The focused application should add a focused window before the timer runs out to prevent ANR.
7071 *
7072 * If the user touches another application during this time, the key should be dropped.
7073 * Next, if a new focused window comes in, without toggling the focused application,
7074 * then no ANR should occur.
7075 *
7076 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
7077 * but in some cases the policy may not update the focused application.
7078 */
7079TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
7080 std::shared_ptr<FakeApplicationHandle> focusedApplication =
7081 std::make_shared<FakeApplicationHandle>();
7082 focusedApplication->setDispatchingTimeout(60ms);
7083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
7084 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
7085 mFocusedWindow->setFocusable(false);
7086
7087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7088 mFocusedWindow->consumeFocusEvent(false);
7089
7090 // Send a key. The ANR timer should start because there is no focused window.
7091 // 'focusedApplication' will get blamed if this timer completes.
7092 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007093 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00007094 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7095 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
7096 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05007098
7099 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
7100 // then the injected touches won't cause the focused event to get dropped.
7101 // The dispatcher only checks for whether the queue should be pruned upon queueing.
7102 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
7103 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
7104 // For this test, it means that the key would get delivered to the window once it becomes
7105 // focused.
7106 std::this_thread::sleep_for(10ms);
7107
7108 // Touch unfocused window. This should force the pending key to get dropped.
7109 NotifyMotionArgs motionArgs =
7110 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7111 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
7112 mDispatcher->notifyMotion(&motionArgs);
7113
7114 // We do not consume the motion right away, because that would require dispatcher to first
7115 // process (== drop) the key event, and by that time, ANR will be raised.
7116 // Set the focused window first.
7117 mFocusedWindow->setFocusable(true);
7118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
7119 setFocusedWindow(mFocusedWindow);
7120 mFocusedWindow->consumeFocusEvent(true);
7121 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
7122 // to another application. This could be a bug / behaviour in the policy.
7123
7124 mUnfocusedWindow->consumeMotionDown();
7125
7126 ASSERT_TRUE(mDispatcher->waitForIdle());
7127 // Should not ANR because we actually have a focused window. It was just added too slowly.
7128 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
7129}
7130
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007131// These tests ensure we cannot send touch events to a window that's positioned behind a window
7132// that has feature NO_INPUT_CHANNEL.
7133// Layout:
7134// Top (closest to user)
7135// mNoInputWindow (above all windows)
7136// mBottomWindow
7137// Bottom (furthest from user)
7138class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
7139 virtual void SetUp() override {
7140 InputDispatcherTest::SetUp();
7141
7142 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007143 mNoInputWindow =
7144 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7145 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00007146 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007147 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007148 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7149 // It's perfectly valid for this window to not have an associated input channel
7150
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007151 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
7152 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007153 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
7154
7155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7156 }
7157
7158protected:
7159 std::shared_ptr<FakeApplicationHandle> mApplication;
7160 sp<FakeWindowHandle> mNoInputWindow;
7161 sp<FakeWindowHandle> mBottomWindow;
7162};
7163
7164TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
7165 PointF touchedPoint = {10, 10};
7166
7167 NotifyMotionArgs motionArgs =
7168 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7169 ADISPLAY_ID_DEFAULT, {touchedPoint});
7170 mDispatcher->notifyMotion(&motionArgs);
7171
7172 mNoInputWindow->assertNoEvents();
7173 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
7174 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
7175 // and therefore should prevent mBottomWindow from receiving touches
7176 mBottomWindow->assertNoEvents();
7177}
7178
7179/**
7180 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
7181 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
7182 */
7183TEST_F(InputDispatcherMultiWindowOcclusionTests,
7184 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007185 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
7186 "Window with input channel and NO_INPUT_CHANNEL",
7187 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007188
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007189 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05007190 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
7191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
7192
7193 PointF touchedPoint = {10, 10};
7194
7195 NotifyMotionArgs motionArgs =
7196 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7197 ADISPLAY_ID_DEFAULT, {touchedPoint});
7198 mDispatcher->notifyMotion(&motionArgs);
7199
7200 mNoInputWindow->assertNoEvents();
7201 mBottomWindow->assertNoEvents();
7202}
7203
Vishnu Nair958da932020-08-21 17:12:37 -07007204class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
7205protected:
7206 std::shared_ptr<FakeApplicationHandle> mApp;
7207 sp<FakeWindowHandle> mWindow;
7208 sp<FakeWindowHandle> mMirror;
7209
7210 virtual void SetUp() override {
7211 InputDispatcherTest::SetUp();
7212 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007213 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
7214 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
7215 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07007216 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7217 mWindow->setFocusable(true);
7218 mMirror->setFocusable(true);
7219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7220 }
7221};
7222
7223TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
7224 // Request focus on a mirrored window
7225 setFocusedWindow(mMirror);
7226
7227 // window gets focused
7228 mWindow->consumeFocusEvent(true);
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);
7232}
7233
7234// A focused & mirrored window remains focused only if the window and its mirror are both
7235// focusable.
7236TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
7237 setFocusedWindow(mMirror);
7238
7239 // window gets focused
7240 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007241 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7242 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007243 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007244 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7245 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007246 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7247
7248 mMirror->setFocusable(false);
7249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7250
7251 // window loses focus since one of the windows associated with the token in not focusable
7252 mWindow->consumeFocusEvent(false);
7253
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007254 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7255 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007256 mWindow->assertNoEvents();
7257}
7258
7259// A focused & mirrored window remains focused until the window and its mirror both become
7260// invisible.
7261TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
7262 setFocusedWindow(mMirror);
7263
7264 // window gets focused
7265 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7267 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007268 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7270 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007271 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7272
7273 mMirror->setVisible(false);
7274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7275
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7277 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007278 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007279 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7280 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007281 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7282
7283 mWindow->setVisible(false);
7284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7285
7286 // window loses focus only after all windows associated with the token become invisible.
7287 mWindow->consumeFocusEvent(false);
7288
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007289 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7290 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007291 mWindow->assertNoEvents();
7292}
7293
7294// A focused & mirrored window remains focused until both windows are removed.
7295TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
7296 setFocusedWindow(mMirror);
7297
7298 // window gets focused
7299 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7301 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007302 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007303 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7304 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007305 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7306
7307 // single window is removed but the window token remains focused
7308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
7309
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7311 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007312 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7314 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07007315 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
7316
7317 // Both windows are removed
7318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
7319 mWindow->consumeFocusEvent(false);
7320
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007321 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
7322 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07007323 mWindow->assertNoEvents();
7324}
7325
7326// Focus request can be pending until one window becomes visible.
7327TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
7328 // Request focus on an invisible mirror.
7329 mWindow->setVisible(false);
7330 mMirror->setVisible(false);
7331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7332 setFocusedWindow(mMirror);
7333
7334 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08007335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00007336 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
7337 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07007338
7339 mMirror->setVisible(true);
7340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
7341
7342 // window gets focused
7343 mWindow->consumeFocusEvent(true);
7344 // window gets the pending key event
7345 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7346}
Prabir Pradhan99987712020-11-10 18:43:05 -08007347
7348class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
7349protected:
7350 std::shared_ptr<FakeApplicationHandle> mApp;
7351 sp<FakeWindowHandle> mWindow;
7352 sp<FakeWindowHandle> mSecondWindow;
7353
7354 void SetUp() override {
7355 InputDispatcherTest::SetUp();
7356 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007357 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007358 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007359 mSecondWindow =
7360 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08007361 mSecondWindow->setFocusable(true);
7362
7363 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
7364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
7365
7366 setFocusedWindow(mWindow);
7367 mWindow->consumeFocusEvent(true);
7368 }
7369
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007370 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
7371 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007372 mDispatcher->notifyPointerCaptureChanged(&args);
7373 }
7374
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007375 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
7376 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007377 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007378 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
7379 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007380 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007381 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08007382 }
7383};
7384
7385TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
7386 // Ensure that capture cannot be obtained for unfocused windows.
7387 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
7388 mFakePolicy->assertSetPointerCaptureNotCalled();
7389 mSecondWindow->assertNoEvents();
7390
7391 // Ensure that capture can be enabled from the focus window.
7392 requestAndVerifyPointerCapture(mWindow, true);
7393
7394 // Ensure that capture cannot be disabled from a window that does not have capture.
7395 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
7396 mFakePolicy->assertSetPointerCaptureNotCalled();
7397
7398 // Ensure that capture can be disabled from the window with capture.
7399 requestAndVerifyPointerCapture(mWindow, false);
7400}
7401
7402TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007403 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007404
7405 setFocusedWindow(mSecondWindow);
7406
7407 // Ensure that the capture disabled event was sent first.
7408 mWindow->consumeCaptureEvent(false);
7409 mWindow->consumeFocusEvent(false);
7410 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007411 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007412
7413 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007414 notifyPointerCaptureChanged({});
7415 notifyPointerCaptureChanged(request);
7416 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08007417 mWindow->assertNoEvents();
7418 mSecondWindow->assertNoEvents();
7419 mFakePolicy->assertSetPointerCaptureNotCalled();
7420}
7421
7422TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007423 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08007424
7425 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007426 notifyPointerCaptureChanged({});
7427 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08007428
7429 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007430 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08007431 mWindow->consumeCaptureEvent(false);
7432 mWindow->assertNoEvents();
7433}
7434
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007435TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
7436 requestAndVerifyPointerCapture(mWindow, true);
7437
7438 // The first window loses focus.
7439 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007440 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007441 mWindow->consumeCaptureEvent(false);
7442
7443 // Request Pointer Capture from the second window before the notification from InputReader
7444 // arrives.
7445 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007446 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007447
7448 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007449 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007450
7451 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007452 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08007453
7454 mSecondWindow->consumeFocusEvent(true);
7455 mSecondWindow->consumeCaptureEvent(true);
7456}
7457
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007458TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
7459 // App repeatedly enables and disables capture.
7460 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7461 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7462 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7463 mFakePolicy->assertSetPointerCaptureCalled(false);
7464 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7465 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7466
7467 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
7468 // first request is now stale, this should do nothing.
7469 notifyPointerCaptureChanged(firstRequest);
7470 mWindow->assertNoEvents();
7471
7472 // InputReader notifies that the second request was enabled.
7473 notifyPointerCaptureChanged(secondRequest);
7474 mWindow->consumeCaptureEvent(true);
7475}
7476
Prabir Pradhan7092e262022-05-03 16:51:09 +00007477TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
7478 requestAndVerifyPointerCapture(mWindow, true);
7479
7480 // App toggles pointer capture off and on.
7481 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
7482 mFakePolicy->assertSetPointerCaptureCalled(false);
7483
7484 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
7485 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
7486
7487 // InputReader notifies that the latest "enable" request was processed, while skipping over the
7488 // preceding "disable" request.
7489 notifyPointerCaptureChanged(enableRequest);
7490
7491 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
7492 // any notifications.
7493 mWindow->assertNoEvents();
7494}
7495
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007496class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
7497protected:
7498 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00007499
7500 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
7501 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
7502
7503 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
7504 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7505
7506 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
7507 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
7508 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
7509 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
7510 MAXIMUM_OBSCURING_OPACITY);
7511
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007512 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007513 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007514 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007515
7516 sp<FakeWindowHandle> mTouchWindow;
7517
7518 virtual void SetUp() override {
7519 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007520 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007521 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
7522 }
7523
7524 virtual void TearDown() override {
7525 InputDispatcherTest::TearDown();
7526 mTouchWindow.clear();
7527 }
7528
chaviw3277faf2021-05-19 16:45:23 -05007529 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
7530 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007531 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007532 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007533 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007534 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007535 return window;
7536 }
7537
7538 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
7539 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
7540 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007541 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007542 // Generate an arbitrary PID based on the UID
7543 window->setOwnerInfo(1777 + (uid % 10000), uid);
7544 return window;
7545 }
7546
7547 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
7548 NotifyMotionArgs args =
7549 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7550 ADISPLAY_ID_DEFAULT, points);
7551 mDispatcher->notifyMotion(&args);
7552 }
7553};
7554
7555TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007556 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007557 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007559
7560 touch();
7561
7562 mTouchWindow->assertNoEvents();
7563}
7564
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007565TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00007566 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
7567 const sp<FakeWindowHandle>& w =
7568 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
7569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7570
7571 touch();
7572
7573 mTouchWindow->assertNoEvents();
7574}
7575
7576TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007577 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
7578 const sp<FakeWindowHandle>& w =
7579 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7581
7582 touch();
7583
7584 w->assertNoEvents();
7585}
7586
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007587TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007588 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
7589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007590
7591 touch();
7592
7593 mTouchWindow->consumeAnyMotionDown();
7594}
7595
7596TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007597 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007598 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007599 w->setFrame(Rect(0, 0, 50, 50));
7600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007601
7602 touch({PointF{100, 100}});
7603
7604 mTouchWindow->consumeAnyMotionDown();
7605}
7606
7607TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007608 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007609 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7611
7612 touch();
7613
7614 mTouchWindow->consumeAnyMotionDown();
7615}
7616
7617TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
7618 const sp<FakeWindowHandle>& w =
7619 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007621
7622 touch();
7623
7624 mTouchWindow->consumeAnyMotionDown();
7625}
7626
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007627TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
7628 const sp<FakeWindowHandle>& w =
7629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
7630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7631
7632 touch();
7633
7634 w->assertNoEvents();
7635}
7636
7637/**
7638 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7639 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7640 * window, the occluding window will still receive ACTION_OUTSIDE event.
7641 */
7642TEST_F(InputDispatcherUntrustedTouchesTest,
7643 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7644 const sp<FakeWindowHandle>& w =
7645 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007646 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7648
7649 touch();
7650
7651 w->consumeMotionOutside();
7652}
7653
7654TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7655 const sp<FakeWindowHandle>& w =
7656 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007657 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7659
7660 touch();
7661
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007662 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007663}
7664
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007665TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007666 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007667 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7668 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7670
7671 touch();
7672
7673 mTouchWindow->consumeAnyMotionDown();
7674}
7675
7676TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7677 const sp<FakeWindowHandle>& w =
7678 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7679 MAXIMUM_OBSCURING_OPACITY);
7680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007681
7682 touch();
7683
7684 mTouchWindow->consumeAnyMotionDown();
7685}
7686
7687TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007688 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007689 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7690 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7692
7693 touch();
7694
7695 mTouchWindow->assertNoEvents();
7696}
7697
7698TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7699 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7700 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007701 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7702 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007703 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007704 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7705 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7707
7708 touch();
7709
7710 mTouchWindow->assertNoEvents();
7711}
7712
7713TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7714 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7715 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007716 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7717 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007718 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007719 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7720 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7722
7723 touch();
7724
7725 mTouchWindow->consumeAnyMotionDown();
7726}
7727
7728TEST_F(InputDispatcherUntrustedTouchesTest,
7729 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7730 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007731 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7732 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007733 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007734 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7735 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7737
7738 touch();
7739
7740 mTouchWindow->consumeAnyMotionDown();
7741}
7742
7743TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7744 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007745 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7746 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007747 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007748 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7749 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007751
7752 touch();
7753
7754 mTouchWindow->assertNoEvents();
7755}
7756
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007757TEST_F(InputDispatcherUntrustedTouchesTest,
7758 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7759 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007760 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7761 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007762 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007763 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7764 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7766
7767 touch();
7768
7769 mTouchWindow->assertNoEvents();
7770}
7771
7772TEST_F(InputDispatcherUntrustedTouchesTest,
7773 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7774 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007775 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7776 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007777 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007778 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7779 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7781
7782 touch();
7783
7784 mTouchWindow->consumeAnyMotionDown();
7785}
7786
7787TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7788 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007789 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7790 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7792
7793 touch();
7794
7795 mTouchWindow->consumeAnyMotionDown();
7796}
7797
7798TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7799 const sp<FakeWindowHandle>& w =
7800 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7802
7803 touch();
7804
7805 mTouchWindow->consumeAnyMotionDown();
7806}
7807
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007808TEST_F(InputDispatcherUntrustedTouchesTest,
7809 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7810 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7811 const sp<FakeWindowHandle>& w =
7812 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7814
7815 touch();
7816
7817 mTouchWindow->assertNoEvents();
7818}
7819
7820TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7821 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7822 const sp<FakeWindowHandle>& w =
7823 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7825
7826 touch();
7827
7828 mTouchWindow->consumeAnyMotionDown();
7829}
7830
7831TEST_F(InputDispatcherUntrustedTouchesTest,
7832 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7833 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7834 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007835 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7836 OPACITY_ABOVE_THRESHOLD);
7837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7838
7839 touch();
7840
7841 mTouchWindow->consumeAnyMotionDown();
7842}
7843
7844TEST_F(InputDispatcherUntrustedTouchesTest,
7845 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7846 const sp<FakeWindowHandle>& w1 =
7847 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7848 OPACITY_BELOW_THRESHOLD);
7849 const sp<FakeWindowHandle>& w2 =
7850 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7851 OPACITY_BELOW_THRESHOLD);
7852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7853
7854 touch();
7855
7856 mTouchWindow->assertNoEvents();
7857}
7858
7859/**
7860 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7861 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7862 * (which alone would result in allowing touches) does not affect the blocking behavior.
7863 */
7864TEST_F(InputDispatcherUntrustedTouchesTest,
7865 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7866 const sp<FakeWindowHandle>& wB =
7867 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7868 OPACITY_BELOW_THRESHOLD);
7869 const sp<FakeWindowHandle>& wC =
7870 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7871 OPACITY_BELOW_THRESHOLD);
7872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7873
7874 touch();
7875
7876 mTouchWindow->assertNoEvents();
7877}
7878
7879/**
7880 * This test is testing that a window from a different UID but with same application token doesn't
7881 * block the touch. Apps can share the application token for close UI collaboration for example.
7882 */
7883TEST_F(InputDispatcherUntrustedTouchesTest,
7884 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7885 const sp<FakeWindowHandle>& w =
7886 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7887 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7889
7890 touch();
7891
7892 mTouchWindow->consumeAnyMotionDown();
7893}
7894
arthurhungb89ccb02020-12-30 16:19:01 +08007895class InputDispatcherDragTests : public InputDispatcherTest {
7896protected:
7897 std::shared_ptr<FakeApplicationHandle> mApp;
7898 sp<FakeWindowHandle> mWindow;
7899 sp<FakeWindowHandle> mSecondWindow;
7900 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007901 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007902 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7903 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007904
7905 void SetUp() override {
7906 InputDispatcherTest::SetUp();
7907 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007908 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007909 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007910
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007911 mSecondWindow =
7912 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007913 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007914
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007915 mSpyWindow =
7916 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007917 mSpyWindow->setSpy(true);
7918 mSpyWindow->setTrustedOverlay(true);
7919 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7920
arthurhungb89ccb02020-12-30 16:19:01 +08007921 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007923 }
7924
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007925 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7926 switch (fromSource) {
7927 case AINPUT_SOURCE_TOUCHSCREEN:
7928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7929 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7930 ADISPLAY_ID_DEFAULT, {50, 50}))
7931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7932 break;
7933 case AINPUT_SOURCE_STYLUS:
7934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7935 injectMotionEvent(
7936 mDispatcher,
7937 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7938 AINPUT_SOURCE_STYLUS)
7939 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7940 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7941 .x(50)
7942 .y(50))
7943 .build()));
7944 break;
7945 case AINPUT_SOURCE_MOUSE:
7946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7947 injectMotionEvent(
7948 mDispatcher,
7949 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7950 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7951 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7952 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7953 .x(50)
7954 .y(50))
7955 .build()));
7956 break;
7957 default:
7958 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7959 }
arthurhungb89ccb02020-12-30 16:19:01 +08007960
7961 // Window should receive motion event.
7962 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007963 // Spy window should also receive motion event
7964 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007965 }
7966
7967 // Start performing drag, we will create a drag window and transfer touch to it.
7968 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7969 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007970 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007971 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007972 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007973 }
arthurhungb89ccb02020-12-30 16:19:01 +08007974
7975 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007976 mDragWindow =
7977 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007978 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007979 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007980 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007981
7982 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007983 bool transferred =
7984 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007985 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007986 if (transferred) {
7987 mWindow->consumeMotionCancel();
7988 mDragWindow->consumeMotionDown();
7989 }
7990 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007991 }
7992};
7993
7994TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007995 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007996
7997 // Move on window.
7998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7999 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8000 ADISPLAY_ID_DEFAULT, {50, 50}))
8001 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8002 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8003 mWindow->consumeDragEvent(false, 50, 50);
8004 mSecondWindow->assertNoEvents();
8005
8006 // Move to another window.
8007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8008 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8009 ADISPLAY_ID_DEFAULT, {150, 50}))
8010 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8011 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8012 mWindow->consumeDragEvent(true, 150, 50);
8013 mSecondWindow->consumeDragEvent(false, 50, 50);
8014
8015 // Move back to original window.
8016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8017 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8018 ADISPLAY_ID_DEFAULT, {50, 50}))
8019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8020 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8021 mWindow->consumeDragEvent(false, 50, 50);
8022 mSecondWindow->consumeDragEvent(true, -50, 50);
8023
8024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8025 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
8026 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8027 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8028 mWindow->assertNoEvents();
8029 mSecondWindow->assertNoEvents();
8030}
8031
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008032TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008033 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008034
8035 // No cancel event after drag start
8036 mSpyWindow->assertNoEvents();
8037
8038 const MotionEvent secondFingerDownEvent =
8039 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8040 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008041 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8042 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00008043 .build();
8044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8045 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8046 InputEventInjectionSync::WAIT_FOR_RESULT))
8047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8048
8049 // Receives cancel for first pointer after next pointer down
8050 mSpyWindow->consumeMotionCancel();
8051 mSpyWindow->consumeMotionDown();
8052
8053 mSpyWindow->assertNoEvents();
8054}
8055
arthurhungf452d0b2021-01-06 00:19:52 +08008056TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008057 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08008058
8059 // Move on window.
8060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8061 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8062 ADISPLAY_ID_DEFAULT, {50, 50}))
8063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8064 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8065 mWindow->consumeDragEvent(false, 50, 50);
8066 mSecondWindow->assertNoEvents();
8067
8068 // Move to another window.
8069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8070 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8071 ADISPLAY_ID_DEFAULT, {150, 50}))
8072 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8073 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8074 mWindow->consumeDragEvent(true, 150, 50);
8075 mSecondWindow->consumeDragEvent(false, 50, 50);
8076
8077 // drop to another window.
8078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8079 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8080 {150, 50}))
8081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8082 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8083 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8084 mWindow->assertNoEvents();
8085 mSecondWindow->assertNoEvents();
8086}
8087
arthurhung6d4bed92021-03-17 11:59:33 +08008088TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008089 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08008090
8091 // Move on window and keep button pressed.
8092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8093 injectMotionEvent(mDispatcher,
8094 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8095 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
8096 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8097 .x(50)
8098 .y(50))
8099 .build()))
8100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8101 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8102 mWindow->consumeDragEvent(false, 50, 50);
8103 mSecondWindow->assertNoEvents();
8104
8105 // Move to another window and release button, expect to drop item.
8106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8107 injectMotionEvent(mDispatcher,
8108 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
8109 .buttonState(0)
8110 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8111 .x(150)
8112 .y(50))
8113 .build()))
8114 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8115 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8116 mWindow->assertNoEvents();
8117 mSecondWindow->assertNoEvents();
8118 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8119
8120 // nothing to the window.
8121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8122 injectMotionEvent(mDispatcher,
8123 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
8124 .buttonState(0)
8125 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
8126 .x(150)
8127 .y(50))
8128 .build()))
8129 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8130 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8131 mWindow->assertNoEvents();
8132 mSecondWindow->assertNoEvents();
8133}
8134
Arthur Hung54745652022-04-20 07:17:41 +00008135TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008136 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08008137
8138 // Set second window invisible.
8139 mSecondWindow->setVisible(false);
8140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
8141
8142 // Move on window.
8143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8144 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8145 ADISPLAY_ID_DEFAULT, {50, 50}))
8146 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8147 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8148 mWindow->consumeDragEvent(false, 50, 50);
8149 mSecondWindow->assertNoEvents();
8150
8151 // Move to another window.
8152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8153 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8154 ADISPLAY_ID_DEFAULT, {150, 50}))
8155 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8156 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8157 mWindow->consumeDragEvent(true, 150, 50);
8158 mSecondWindow->assertNoEvents();
8159
8160 // drop to another window.
8161 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8162 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8163 {150, 50}))
8164 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8165 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8166 mFakePolicy->assertDropTargetEquals(nullptr);
8167 mWindow->assertNoEvents();
8168 mSecondWindow->assertNoEvents();
8169}
8170
Arthur Hung54745652022-04-20 07:17:41 +00008171TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008172 // Ensure window could track pointerIds if it didn't support split touch.
8173 mWindow->setPreventSplitting(true);
8174
Arthur Hung54745652022-04-20 07:17:41 +00008175 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8176 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8177 {50, 50}))
8178 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8179 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8180
8181 const MotionEvent secondFingerDownEvent =
8182 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8183 .displayId(ADISPLAY_ID_DEFAULT)
8184 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008185 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8186 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008187 .build();
8188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8189 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8190 InputEventInjectionSync::WAIT_FOR_RESULT))
8191 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008192 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00008193
8194 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008195 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008196}
8197
8198TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
8199 // First down on second window.
8200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8202 {150, 50}))
8203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8204
8205 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8206
8207 // Second down on first window.
8208 const MotionEvent secondFingerDownEvent =
8209 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8210 .displayId(ADISPLAY_ID_DEFAULT)
8211 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008212 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8213 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008214 .build();
8215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8216 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8217 InputEventInjectionSync::WAIT_FOR_RESULT))
8218 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8219 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8220
8221 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008222 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00008223
8224 // Move on window.
8225 const MotionEvent secondFingerMoveEvent =
8226 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
8227 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008228 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8229 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008230 .build();
8231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8232 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
8233 InputEventInjectionSync::WAIT_FOR_RESULT));
8234 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8235 mWindow->consumeDragEvent(false, 50, 50);
8236 mSecondWindow->consumeMotionMove();
8237
8238 // Release the drag pointer should perform drop.
8239 const MotionEvent secondFingerUpEvent =
8240 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
8241 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008242 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
8243 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00008244 .build();
8245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8246 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
8247 InputEventInjectionSync::WAIT_FOR_RESULT));
8248 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8249 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
8250 mWindow->assertNoEvents();
8251 mSecondWindow->consumeMotionMove();
8252}
8253
Arthur Hung3915c1f2022-05-31 07:17:17 +00008254TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008255 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00008256
8257 // Update window of second display.
8258 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008259 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008260 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8261
8262 // Let second display has a touch state.
8263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8264 injectMotionEvent(mDispatcher,
8265 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
8266 AINPUT_SOURCE_TOUCHSCREEN)
8267 .displayId(SECOND_DISPLAY_ID)
8268 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
8269 .x(100)
8270 .y(100))
8271 .build()));
8272 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00008273 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00008274 // Update window again.
8275 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
8276
8277 // Move on window.
8278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8279 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8280 ADISPLAY_ID_DEFAULT, {50, 50}))
8281 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8282 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8283 mWindow->consumeDragEvent(false, 50, 50);
8284 mSecondWindow->assertNoEvents();
8285
8286 // Move to another window.
8287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8288 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8289 ADISPLAY_ID_DEFAULT, {150, 50}))
8290 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8291 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8292 mWindow->consumeDragEvent(true, 150, 50);
8293 mSecondWindow->consumeDragEvent(false, 50, 50);
8294
8295 // drop to another window.
8296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8297 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8298 {150, 50}))
8299 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8300 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8301 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8302 mWindow->assertNoEvents();
8303 mSecondWindow->assertNoEvents();
8304}
8305
Arthur Hungb75c2aa2022-07-15 09:35:36 +00008306TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
8307 startDrag(true, AINPUT_SOURCE_MOUSE);
8308 // Move on window.
8309 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8310 injectMotionEvent(mDispatcher,
8311 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8312 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8313 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8314 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8315 .x(50)
8316 .y(50))
8317 .build()))
8318 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8319 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8320 mWindow->consumeDragEvent(false, 50, 50);
8321 mSecondWindow->assertNoEvents();
8322
8323 // Move to another window.
8324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8325 injectMotionEvent(mDispatcher,
8326 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
8327 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
8328 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8329 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8330 .x(150)
8331 .y(50))
8332 .build()))
8333 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8334 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
8335 mWindow->consumeDragEvent(true, 150, 50);
8336 mSecondWindow->consumeDragEvent(false, 50, 50);
8337
8338 // drop to another window.
8339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8340 injectMotionEvent(mDispatcher,
8341 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
8342 .buttonState(0)
8343 .pointer(PointerBuilder(MOUSE_POINTER_ID,
8344 AMOTION_EVENT_TOOL_TYPE_MOUSE)
8345 .x(150)
8346 .y(50))
8347 .build()))
8348 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8349 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8350 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
8351 mWindow->assertNoEvents();
8352 mSecondWindow->assertNoEvents();
8353}
8354
Vishnu Nair062a8672021-09-03 16:07:44 -07008355class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
8356
8357TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
8358 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008359 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8360 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008361 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008362 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8363 window->setFocusable(true);
8364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8365 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008366 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008367
8368 // With the flag set, window should not get any input
8369 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8370 mDispatcher->notifyKey(&keyArgs);
8371 window->assertNoEvents();
8372
8373 NotifyMotionArgs motionArgs =
8374 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8375 ADISPLAY_ID_DEFAULT);
8376 mDispatcher->notifyMotion(&motionArgs);
8377 window->assertNoEvents();
8378
8379 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008380 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8382
8383 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8384 mDispatcher->notifyKey(&keyArgs);
8385 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8386
8387 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8388 ADISPLAY_ID_DEFAULT);
8389 mDispatcher->notifyMotion(&motionArgs);
8390 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8391 window->assertNoEvents();
8392}
8393
8394TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
8395 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8396 std::make_shared<FakeApplicationHandle>();
8397 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008398 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8399 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008400 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8401 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008402 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008404 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8405 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008406 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008407 window->setOwnerInfo(222, 222);
8408 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8409 window->setFocusable(true);
8410 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8411 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008412 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008413
8414 // With the flag set, window should not get any input
8415 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8416 mDispatcher->notifyKey(&keyArgs);
8417 window->assertNoEvents();
8418
8419 NotifyMotionArgs motionArgs =
8420 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8421 ADISPLAY_ID_DEFAULT);
8422 mDispatcher->notifyMotion(&motionArgs);
8423 window->assertNoEvents();
8424
8425 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008426 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8428
8429 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8430 mDispatcher->notifyKey(&keyArgs);
8431 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8432
8433 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8434 ADISPLAY_ID_DEFAULT);
8435 mDispatcher->notifyMotion(&motionArgs);
8436 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
8437 window->assertNoEvents();
8438}
8439
8440TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
8441 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
8442 std::make_shared<FakeApplicationHandle>();
8443 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008444 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
8445 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07008446 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
8447 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008448 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07008449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008450 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
8451 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008452 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008453 window->setOwnerInfo(222, 222);
8454 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8455 window->setFocusable(true);
8456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
8457 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008458 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07008459
8460 // With the flag set, window should not get any input
8461 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
8462 mDispatcher->notifyKey(&keyArgs);
8463 window->assertNoEvents();
8464
8465 NotifyMotionArgs motionArgs =
8466 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8467 ADISPLAY_ID_DEFAULT);
8468 mDispatcher->notifyMotion(&motionArgs);
8469 window->assertNoEvents();
8470
8471 // When the window is no longer obscured because it went on top, it should get input
8472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
8473
8474 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
8475 mDispatcher->notifyKey(&keyArgs);
8476 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
8477
8478 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8479 ADISPLAY_ID_DEFAULT);
8480 mDispatcher->notifyMotion(&motionArgs);
8481 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8482 window->assertNoEvents();
8483}
8484
Antonio Kantekf16f2832021-09-28 04:39:20 +00008485class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
8486protected:
8487 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00008488 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008489 sp<FakeWindowHandle> mWindow;
8490 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00008491 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00008492
8493 void SetUp() override {
8494 InputDispatcherTest::SetUp();
8495
8496 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00008497 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008498 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008499 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008500 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008501 mSecondWindow =
8502 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008503 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00008504 mThirdWindow =
8505 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
8506 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
8507 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008508
8509 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00008510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
8511 {SECOND_DISPLAY_ID, {mThirdWindow}}});
8512 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008513 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008514
Antonio Kantek15beb512022-06-13 22:35:41 +00008515 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00008516 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008517 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07008518 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
8519 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008520 mThirdWindow->assertNoEvents();
8521 }
8522
8523 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
8524 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00008525 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00008526 SECOND_DISPLAY_ID)) {
8527 mWindow->assertNoEvents();
8528 mSecondWindow->assertNoEvents();
8529 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07008530 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00008531 }
8532
Antonio Kantek15beb512022-06-13 22:35:41 +00008533 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
8534 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07008535 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
8536 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008537 mWindow->consumeTouchModeEvent(inTouchMode);
8538 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00008539 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00008540 }
8541};
8542
Antonio Kantek26defcf2022-02-08 01:12:27 +00008543TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008544 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00008545 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
8546 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008547 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00008548}
8549
Antonio Kantek26defcf2022-02-08 01:12:27 +00008550TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
8551 const WindowInfo& windowInfo = *mWindow->getInfo();
8552 int32_t ownerPid = windowInfo.ownerPid;
8553 int32_t ownerUid = windowInfo.ownerUid;
8554 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
8555 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008556 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07008557 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00008558 mWindow->assertNoEvents();
8559 mSecondWindow->assertNoEvents();
8560}
8561
8562TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
8563 const WindowInfo& windowInfo = *mWindow->getInfo();
8564 int32_t ownerPid = windowInfo.ownerPid;
8565 int32_t ownerUid = windowInfo.ownerUid;
8566 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00008567 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00008568 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00008569}
8570
Antonio Kantekf16f2832021-09-28 04:39:20 +00008571TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08008572 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00008573 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
8574 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008575 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00008576 mWindow->assertNoEvents();
8577 mSecondWindow->assertNoEvents();
8578}
8579
Antonio Kantek15beb512022-06-13 22:35:41 +00008580TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
8581 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
8582 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8583 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008584 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00008585 mWindow->assertNoEvents();
8586 mSecondWindow->assertNoEvents();
8587 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
8588}
8589
Antonio Kantek48710e42022-03-24 14:19:30 -07008590TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
8591 // Interact with the window first.
8592 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
8593 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8594 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
8595
8596 // Then remove focus.
8597 mWindow->setFocusable(false);
8598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
8599
8600 // Assert that caller can switch touch mode by owning one of the last interacted window.
8601 const WindowInfo& windowInfo = *mWindow->getInfo();
8602 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
8603 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00008604 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07008605}
8606
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008607class InputDispatcherSpyWindowTest : public InputDispatcherTest {
8608public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008609 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008610 std::shared_ptr<FakeApplicationHandle> application =
8611 std::make_shared<FakeApplicationHandle>();
8612 std::string name = "Fake Spy ";
8613 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008614 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
8615 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008616 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008617 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008618 return spy;
8619 }
8620
8621 sp<FakeWindowHandle> createForeground() {
8622 std::shared_ptr<FakeApplicationHandle> application =
8623 std::make_shared<FakeApplicationHandle>();
8624 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008625 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
8626 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008627 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008628 return window;
8629 }
8630
8631private:
8632 int mSpyCount{0};
8633};
8634
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008635using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008636/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008637 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8638 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008639TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8640 ScopedSilentDeath _silentDeath;
8641
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008642 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008643 spy->setTrustedOverlay(false);
8644 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8645 ".* not a trusted overlay");
8646}
8647
8648/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008649 * Input injection into a display with a spy window but no foreground windows should succeed.
8650 */
8651TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008652 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8654
8655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8657 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8658 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8659}
8660
8661/**
8662 * Verify the order in which different input windows receive events. The touched foreground window
8663 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8664 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8665 * receive events before ones belows it.
8666 *
8667 * Here, we set up a scenario with four windows in the following Z order from the top:
8668 * spy1, spy2, window, spy3.
8669 * We then inject an event and verify that the foreground "window" receives it first, followed by
8670 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8671 * window.
8672 */
8673TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8674 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008675 auto spy1 = createSpy();
8676 auto spy2 = createSpy();
8677 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8679 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8680 const size_t numChannels = channels.size();
8681
Michael Wright8e9a8562022-02-09 13:44:29 +00008682 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008683 if (!epollFd.ok()) {
8684 FAIL() << "Failed to create epoll fd";
8685 }
8686
8687 for (size_t i = 0; i < numChannels; i++) {
8688 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8689 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8690 FAIL() << "Failed to add fd to epoll";
8691 }
8692 }
8693
8694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8695 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8696 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8697
8698 std::vector<size_t> eventOrder;
8699 std::vector<struct epoll_event> events(numChannels);
8700 for (;;) {
8701 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8702 (100ms).count());
8703 if (nFds < 0) {
8704 FAIL() << "Failed to call epoll_wait";
8705 }
8706 if (nFds == 0) {
8707 break; // epoll_wait timed out
8708 }
8709 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008710 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008711 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008712 channels[i]->consumeMotionDown();
8713 }
8714 }
8715
8716 // Verify the order in which the events were received.
8717 EXPECT_EQ(3u, eventOrder.size());
8718 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8719 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8720 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8721}
8722
8723/**
8724 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8725 */
8726TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8727 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008728 auto spy = createSpy();
8729 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8731
8732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8735 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8736 spy->assertNoEvents();
8737}
8738
8739/**
8740 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8741 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8742 * to the window.
8743 */
8744TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8745 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008746 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008747 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8749
8750 // Inject an event outside the spy window's touchable region.
8751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8752 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8754 window->consumeMotionDown();
8755 spy->assertNoEvents();
8756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8757 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8758 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8759 window->consumeMotionUp();
8760 spy->assertNoEvents();
8761
8762 // Inject an event inside the spy window's touchable region.
8763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8764 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8765 {5, 10}))
8766 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8767 window->consumeMotionDown();
8768 spy->consumeMotionDown();
8769}
8770
8771/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008772 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008773 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008774 */
8775TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8776 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008777 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008778 auto spy = createSpy();
8779 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008780 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008781 spy->setFrame(Rect{0, 0, 20, 20});
8782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8783
8784 // Inject an event outside the spy window's frame and touchable region.
8785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8787 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8789 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008790 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008791}
8792
8793/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008794 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8795 * pointers that are down within its bounds.
8796 */
8797TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8798 auto windowLeft = createForeground();
8799 windowLeft->setFrame({0, 0, 100, 200});
8800 auto windowRight = createForeground();
8801 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008802 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008803 spy->setFrame({0, 0, 200, 200});
8804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8805
8806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8807 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8808 {50, 50}))
8809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8810 windowLeft->consumeMotionDown();
8811 spy->consumeMotionDown();
8812
8813 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008814 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008815 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008816 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8817 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008818 .build();
8819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8820 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8821 InputEventInjectionSync::WAIT_FOR_RESULT))
8822 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8823 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008824 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008825}
8826
8827/**
8828 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8829 * the spy should receive the second pointer with ACTION_DOWN.
8830 */
8831TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8832 auto window = createForeground();
8833 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008834 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008835 spyRight->setFrame({100, 0, 200, 200});
8836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8837
8838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8839 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8840 {50, 50}))
8841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8842 window->consumeMotionDown();
8843 spyRight->assertNoEvents();
8844
8845 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008846 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008847 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008848 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8849 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008850 .build();
8851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8852 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8853 InputEventInjectionSync::WAIT_FOR_RESULT))
8854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008855 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008856 spyRight->consumeMotionDown();
8857}
8858
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008859/**
8860 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8861 * windows should be allowed to control split touch.
8862 */
8863TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008864 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008865 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008866 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008867 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008868
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008869 auto window = createForeground();
8870 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008871
8872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8873
8874 // First finger down, no window touched.
8875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8876 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8877 {100, 200}))
8878 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8879 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8880 window->assertNoEvents();
8881
8882 // Second finger down on window, the window should receive touch down.
8883 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008884 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008885 .displayId(ADISPLAY_ID_DEFAULT)
8886 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008887 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8888 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008889 .build();
8890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8891 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8892 InputEventInjectionSync::WAIT_FOR_RESULT))
8893 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8894
8895 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008896 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008897}
8898
8899/**
8900 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8901 * do not receive key events.
8902 */
8903TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008904 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008905 spy->setFocusable(false);
8906
8907 auto window = createForeground();
8908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8909 setFocusedWindow(window);
8910 window->consumeFocusEvent(true);
8911
8912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8913 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8914 window->consumeKeyDown(ADISPLAY_ID_NONE);
8915
8916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8917 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8918 window->consumeKeyUp(ADISPLAY_ID_NONE);
8919
8920 spy->assertNoEvents();
8921}
8922
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008923using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8924
8925/**
8926 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8927 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8928 */
8929TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8930 auto window = createForeground();
8931 auto spy1 = createSpy();
8932 auto spy2 = createSpy();
8933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8934
8935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8938 window->consumeMotionDown();
8939 spy1->consumeMotionDown();
8940 spy2->consumeMotionDown();
8941
8942 // Pilfer pointers from the second spy window.
8943 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8944 spy2->assertNoEvents();
8945 spy1->consumeMotionCancel();
8946 window->consumeMotionCancel();
8947
8948 // The rest of the gesture should only be sent to the second spy window.
8949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8950 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8951 ADISPLAY_ID_DEFAULT))
8952 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8953 spy2->consumeMotionMove();
8954 spy1->assertNoEvents();
8955 window->assertNoEvents();
8956}
8957
8958/**
8959 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8960 * in the middle of the gesture.
8961 */
8962TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8963 auto window = createForeground();
8964 auto spy = createSpy();
8965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8966
8967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8968 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8969 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8970 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8971 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8972
8973 window->releaseChannel();
8974
8975 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8976
8977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8978 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8979 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8980 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8981}
8982
8983/**
8984 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8985 * the spy, but not to any other windows.
8986 */
8987TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8988 auto spy = createSpy();
8989 auto window = createForeground();
8990
8991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8992
8993 // First finger down on the window and the spy.
8994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8995 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8996 {100, 200}))
8997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8998 spy->consumeMotionDown();
8999 window->consumeMotionDown();
9000
9001 // Spy window pilfers the pointers.
9002 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9003 window->consumeMotionCancel();
9004
9005 // Second finger down on the window and spy, but the window should not receive the pointer down.
9006 const MotionEvent secondFingerDownEvent =
9007 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9008 .displayId(ADISPLAY_ID_DEFAULT)
9009 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009010 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
9011 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009012 .build();
9013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9014 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9015 InputEventInjectionSync::WAIT_FOR_RESULT))
9016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9017
Harry Cutts33476232023-01-30 19:57:29 +00009018 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009019
9020 // Third finger goes down outside all windows, so injection should fail.
9021 const MotionEvent thirdFingerDownEvent =
9022 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9023 .displayId(ADISPLAY_ID_DEFAULT)
9024 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009025 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
9026 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
9027 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009028 .build();
9029 ASSERT_EQ(InputEventInjectionResult::FAILED,
9030 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
9031 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08009032 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009033
9034 spy->assertNoEvents();
9035 window->assertNoEvents();
9036}
9037
9038/**
9039 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
9040 */
9041TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
9042 auto spy = createSpy();
9043 spy->setFrame(Rect(0, 0, 100, 100));
9044 auto window = createForeground();
9045 window->setFrame(Rect(0, 0, 200, 200));
9046
9047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9048
9049 // First finger down on the window only
9050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9051 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9052 {150, 150}))
9053 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9054 window->consumeMotionDown();
9055
9056 // Second finger down on the spy and window
9057 const MotionEvent secondFingerDownEvent =
9058 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9059 .displayId(ADISPLAY_ID_DEFAULT)
9060 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009061 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
9062 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009063 .build();
9064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9065 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9066 InputEventInjectionSync::WAIT_FOR_RESULT))
9067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9068 spy->consumeMotionDown();
9069 window->consumeMotionPointerDown(1);
9070
9071 // Third finger down on the spy and window
9072 const MotionEvent thirdFingerDownEvent =
9073 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9074 .displayId(ADISPLAY_ID_DEFAULT)
9075 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009076 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
9077 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9078 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009079 .build();
9080 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9081 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
9082 InputEventInjectionSync::WAIT_FOR_RESULT))
9083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9084 spy->consumeMotionPointerDown(1);
9085 window->consumeMotionPointerDown(2);
9086
9087 // Spy window pilfers the pointers.
9088 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9089 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9090 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
9091
9092 spy->assertNoEvents();
9093 window->assertNoEvents();
9094}
9095
9096/**
9097 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
9098 * other windows should be canceled. If this results in the cancellation of all pointers for some
9099 * window, then that window should receive ACTION_CANCEL.
9100 */
9101TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
9102 auto spy = createSpy();
9103 spy->setFrame(Rect(0, 0, 100, 100));
9104 auto window = createForeground();
9105 window->setFrame(Rect(0, 0, 200, 200));
9106
9107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9108
9109 // First finger down on both spy and window
9110 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9111 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9112 {10, 10}))
9113 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9114 window->consumeMotionDown();
9115 spy->consumeMotionDown();
9116
9117 // Second finger down on the spy and window
9118 const MotionEvent secondFingerDownEvent =
9119 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9120 .displayId(ADISPLAY_ID_DEFAULT)
9121 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009122 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9123 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009124 .build();
9125 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9126 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9127 InputEventInjectionSync::WAIT_FOR_RESULT))
9128 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9129 spy->consumeMotionPointerDown(1);
9130 window->consumeMotionPointerDown(1);
9131
9132 // Spy window pilfers the pointers.
9133 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9134 window->consumeMotionCancel();
9135
9136 spy->assertNoEvents();
9137 window->assertNoEvents();
9138}
9139
9140/**
9141 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
9142 * be sent to other windows
9143 */
9144TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
9145 auto spy = createSpy();
9146 spy->setFrame(Rect(0, 0, 100, 100));
9147 auto window = createForeground();
9148 window->setFrame(Rect(0, 0, 200, 200));
9149
9150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9151
9152 // First finger down on both window and spy
9153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9154 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
9155 {10, 10}))
9156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9157 window->consumeMotionDown();
9158 spy->consumeMotionDown();
9159
9160 // Spy window pilfers the pointers.
9161 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
9162 window->consumeMotionCancel();
9163
9164 // Second finger down on the window only
9165 const MotionEvent secondFingerDownEvent =
9166 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
9167 .displayId(ADISPLAY_ID_DEFAULT)
9168 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00009169 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
9170 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00009171 .build();
9172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
9173 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
9174 InputEventInjectionSync::WAIT_FOR_RESULT))
9175 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
9176 window->consumeMotionDown();
9177 window->assertNoEvents();
9178
9179 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
9180 spy->consumeMotionMove();
9181 spy->assertNoEvents();
9182}
9183
Prabir Pradhand65552b2021-10-07 11:23:50 -07009184class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
9185public:
9186 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
9187 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9188 std::make_shared<FakeApplicationHandle>();
9189 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009190 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
9191 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009192 overlay->setFocusable(false);
9193 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08009194 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009195 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009196 overlay->setTrustedOverlay(true);
9197
9198 std::shared_ptr<FakeApplicationHandle> application =
9199 std::make_shared<FakeApplicationHandle>();
9200 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009201 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
9202 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009203 window->setFocusable(true);
9204 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009205
9206 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
9207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9208 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00009209 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009210 return {std::move(overlay), std::move(window)};
9211 }
9212
9213 void sendFingerEvent(int32_t action) {
9214 NotifyMotionArgs motionArgs =
9215 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9216 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
9217 mDispatcher->notifyMotion(&motionArgs);
9218 }
9219
9220 void sendStylusEvent(int32_t action) {
9221 NotifyMotionArgs motionArgs =
9222 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
9223 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
9224 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
9225 mDispatcher->notifyMotion(&motionArgs);
9226 }
9227};
9228
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08009229using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
9230
9231TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
9232 ScopedSilentDeath _silentDeath;
9233
Prabir Pradhand65552b2021-10-07 11:23:50 -07009234 auto [overlay, window] = setupStylusOverlayScenario();
9235 overlay->setTrustedOverlay(false);
9236 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
9237 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
9238 ".* not a trusted overlay");
9239}
9240
9241TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
9242 auto [overlay, window] = setupStylusOverlayScenario();
9243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9244
9245 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9246 overlay->consumeMotionDown();
9247 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9248 overlay->consumeMotionUp();
9249
9250 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9251 window->consumeMotionDown();
9252 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9253 window->consumeMotionUp();
9254
9255 overlay->assertNoEvents();
9256 window->assertNoEvents();
9257}
9258
9259TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
9260 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08009261 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07009262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9263
9264 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9265 overlay->consumeMotionDown();
9266 window->consumeMotionDown();
9267 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9268 overlay->consumeMotionUp();
9269 window->consumeMotionUp();
9270
9271 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
9272 window->consumeMotionDown();
9273 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
9274 window->consumeMotionUp();
9275
9276 overlay->assertNoEvents();
9277 window->assertNoEvents();
9278}
9279
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00009280/**
9281 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
9282 * The scenario is as follows:
9283 * - The stylus interceptor overlay is configured as a spy window.
9284 * - The stylus interceptor spy receives the start of a new stylus gesture.
9285 * - It pilfers pointers and then configures itself to no longer be a spy.
9286 * - The stylus interceptor continues to receive the rest of the gesture.
9287 */
9288TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
9289 auto [overlay, window] = setupStylusOverlayScenario();
9290 overlay->setSpy(true);
9291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9292
9293 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
9294 overlay->consumeMotionDown();
9295 window->consumeMotionDown();
9296
9297 // The interceptor pilfers the pointers.
9298 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
9299 window->consumeMotionCancel();
9300
9301 // The interceptor configures itself so that it is no longer a spy.
9302 overlay->setSpy(false);
9303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
9304
9305 // It continues to receive the rest of the stylus gesture.
9306 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
9307 overlay->consumeMotionMove();
9308 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
9309 overlay->consumeMotionUp();
9310
9311 window->assertNoEvents();
9312}
9313
Prabir Pradhan5735a322022-04-11 17:23:34 +00009314struct User {
9315 int32_t mPid;
9316 int32_t mUid;
9317 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
9318 std::unique_ptr<InputDispatcher>& mDispatcher;
9319
9320 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
9321 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
9322
9323 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
9324 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
9325 ADISPLAY_ID_DEFAULT, {100, 200},
9326 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
9327 AMOTION_EVENT_INVALID_CURSOR_POSITION},
9328 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
9329 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
9330 }
9331
9332 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00009333 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00009334 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00009335 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00009336 mPolicyFlags);
9337 }
9338
9339 sp<FakeWindowHandle> createWindow() const {
9340 std::shared_ptr<FakeApplicationHandle> overlayApplication =
9341 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07009342 sp<FakeWindowHandle> window =
9343 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
9344 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00009345 window->setOwnerInfo(mPid, mUid);
9346 return window;
9347 }
9348};
9349
9350using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
9351
9352TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
9353 auto owner = User(mDispatcher, 10, 11);
9354 auto window = owner.createWindow();
9355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9356
9357 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9358 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9359 window->consumeMotionDown();
9360
9361 setFocusedWindow(window);
9362 window->consumeFocusEvent(true);
9363
9364 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9365 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9366 window->consumeKeyDown(ADISPLAY_ID_NONE);
9367}
9368
9369TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
9370 auto owner = User(mDispatcher, 10, 11);
9371 auto window = owner.createWindow();
9372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
9373
9374 auto rando = User(mDispatcher, 20, 21);
9375 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9376 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9377
9378 setFocusedWindow(window);
9379 window->consumeFocusEvent(true);
9380
9381 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
9382 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
9383 window->assertNoEvents();
9384}
9385
9386TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
9387 auto owner = User(mDispatcher, 10, 11);
9388 auto window = owner.createWindow();
9389 auto spy = owner.createWindow();
9390 spy->setSpy(true);
9391 spy->setTrustedOverlay(true);
9392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
9393
9394 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9395 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9396 spy->consumeMotionDown();
9397 window->consumeMotionDown();
9398}
9399
9400TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
9401 auto owner = User(mDispatcher, 10, 11);
9402 auto window = owner.createWindow();
9403
9404 auto rando = User(mDispatcher, 20, 21);
9405 auto randosSpy = rando.createWindow();
9406 randosSpy->setSpy(true);
9407 randosSpy->setTrustedOverlay(true);
9408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9409
9410 // The event is targeted at owner's window, so injection should succeed, but the spy should
9411 // not receive the event.
9412 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9413 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9414 randosSpy->assertNoEvents();
9415 window->consumeMotionDown();
9416}
9417
9418TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
9419 auto owner = User(mDispatcher, 10, 11);
9420 auto window = owner.createWindow();
9421
9422 auto rando = User(mDispatcher, 20, 21);
9423 auto randosSpy = rando.createWindow();
9424 randosSpy->setSpy(true);
9425 randosSpy->setTrustedOverlay(true);
9426 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
9427
9428 // A user that has injection permission can inject into any window.
9429 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9430 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
9431 ADISPLAY_ID_DEFAULT));
9432 randosSpy->consumeMotionDown();
9433 window->consumeMotionDown();
9434
9435 setFocusedWindow(randosSpy);
9436 randosSpy->consumeFocusEvent(true);
9437
9438 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
9439 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
9440 window->assertNoEvents();
9441}
9442
9443TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
9444 auto owner = User(mDispatcher, 10, 11);
9445 auto window = owner.createWindow();
9446
9447 auto rando = User(mDispatcher, 20, 21);
9448 auto randosWindow = rando.createWindow();
9449 randosWindow->setFrame(Rect{-10, -10, -5, -5});
9450 randosWindow->setWatchOutsideTouch(true);
9451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
9452
9453 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
9454 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
9455 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
9456 window->consumeMotionDown();
9457 randosWindow->consumeMotionOutside();
9458}
9459
Garfield Tane84e6f92019-08-29 17:28:41 -07009460} // namespace android::inputdispatcher