blob: b1b6e058e4a094c15d6298a466b933aed9368eb2 [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 Vishniakou487c49b2022-12-02 15:48:57 -080061static constexpr int32_t ACTION_OUTSIDE = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -080062static constexpr int32_t ACTION_CANCEL = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080063static constexpr int32_t POINTER_1_DOWN =
64 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000065static constexpr int32_t POINTER_2_DOWN =
66 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000067static constexpr int32_t POINTER_3_DOWN =
68 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Arthur Hungc539dbb2022-12-08 07:45:36 +000069static constexpr int32_t POINTER_0_UP =
70 AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080071static constexpr int32_t POINTER_1_UP =
72 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
73
Antonio Kantek15beb512022-06-13 22:35:41 +000074// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000075static constexpr int32_t WINDOW_PID = 999;
76static constexpr int32_t WINDOW_UID = 1001;
77
Antonio Kantek15beb512022-06-13 22:35:41 +000078// The default pid and uid for the windows created on the secondary display by the test.
79static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
80static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
81
Prabir Pradhan5735a322022-04-11 17:23:34 +000082// The default policy flags to use for event injection by tests.
83static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000085// An arbitrary pid of the gesture monitor window
86static constexpr int32_t MONITOR_PID = 2001;
87
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080088static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
89
Arthur Hungc539dbb2022-12-08 07:45:36 +000090static constexpr int expectedWallpaperFlags =
91 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
92
chaviwd1c23182019-12-20 18:44:56 -080093struct PointF {
94 float x;
95 float y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -080096 auto operator<=>(const PointF&) const = default;
chaviwd1c23182019-12-20 18:44:56 -080097};
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Gang Wang342c9272020-01-13 13:15:04 -050099/**
100 * Return a DOWN key event with KEYCODE_A.
101 */
102static KeyEvent getTestKeyEvent() {
103 KeyEvent event;
104
Garfield Tanfbe732e2020-01-24 11:26:14 -0800105 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
106 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
107 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -0500108 return event;
109}
110
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000111static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
112 ASSERT_EQ(expectedAction, receivedAction)
113 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
114 << MotionEvent::actionToString(receivedAction);
115}
116
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800117MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
118 bool matches = action == arg.getAction();
119 if (!matches) {
120 *result_listener << "expected action " << MotionEvent::actionToString(action)
121 << ", but got " << MotionEvent::actionToString(arg.getAction());
122 }
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800123 if (action == AMOTION_EVENT_ACTION_DOWN) {
124 if (!matches) {
125 *result_listener << "; ";
126 }
127 *result_listener << "downTime should match eventTime for ACTION_DOWN events";
128 matches &= arg.getDownTime() == arg.getEventTime();
129 }
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800130 if (action == AMOTION_EVENT_ACTION_CANCEL) {
131 if (!matches) {
132 *result_listener << "; ";
133 }
134 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
135 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
136 }
137 return matches;
138}
139
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -0800140MATCHER_P(WithDownTime, downTime, "InputEvent with specified downTime") {
141 return arg.getDownTime() == downTime;
142}
143
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800144MATCHER_P(WithDisplayId, displayId, "InputEvent with specified displayId") {
145 return arg.getDisplayId() == displayId;
146}
147
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800148MATCHER_P(WithSource, source, "InputEvent with specified source") {
149 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
150 << inputEventSourceToString(arg.getSource());
151 return arg.getSource() == source;
152}
153
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800154MATCHER_P(WithFlags, flags, "InputEvent with specified flags") {
155 return arg.getFlags() == flags;
156}
157
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800158MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
159 if (arg.getPointerCount() != 1) {
160 *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
161 return false;
162 }
Harry Cutts33476232023-01-30 19:57:29 +0000163 return arg.getX(/*pointerIndex=*/0) == x && arg.getY(/*pointerIndex=*/0) == y;
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -0800164}
165
166MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
167 // Build a map for the received pointers, by pointer id
168 std::map<int32_t /*pointerId*/, PointF> actualPointers;
169 for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
170 const int32_t pointerId = arg.getPointerId(pointerIndex);
171 actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
172 }
173 return pointers == actualPointers;
174}
175
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176// --- FakeInputDispatcherPolicy ---
177
178class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
179 InputDispatcherConfiguration mConfig;
180
Prabir Pradhanedd96402022-02-15 01:46:16 -0800181 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
182
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000184 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185
186public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000187 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800188
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800189 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700190 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
191 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
192 EXPECT_EQ(event.getDisplayId(), args.displayId);
193
194 const auto& keyEvent = static_cast<const KeyEvent&>(event);
195 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
196 EXPECT_EQ(keyEvent.getAction(), args.action);
197 });
Jackal Guof9696682018-10-05 12:23:23 +0800198 }
199
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700200 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
201 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
202 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
203 EXPECT_EQ(event.getDisplayId(), args.displayId);
204
205 const auto& motionEvent = static_cast<const MotionEvent&>(event);
206 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
207 EXPECT_EQ(motionEvent.getAction(), args.action);
208 EXPECT_EQ(motionEvent.getX(0), point.x);
209 EXPECT_EQ(motionEvent.getY(0), point.y);
210 EXPECT_EQ(motionEvent.getRawX(0), point.x);
211 EXPECT_EQ(motionEvent.getRawY(0), point.y);
212 });
Jackal Guof9696682018-10-05 12:23:23 +0800213 }
214
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700215 void assertFilterInputEventWasNotCalled() {
216 std::scoped_lock lock(mLock);
217 ASSERT_EQ(nullptr, mFilteredEvent);
218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800220 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700221 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800222 ASSERT_TRUE(mConfigurationChangedTime)
223 << "Timed out waiting for configuration changed call";
224 ASSERT_EQ(*mConfigurationChangedTime, when);
225 mConfigurationChangedTime = std::nullopt;
226 }
227
228 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700229 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800230 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800231 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800232 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
233 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
234 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
235 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
236 mLastNotifySwitch = std::nullopt;
237 }
238
chaviwfd6d3512019-03-25 13:23:49 -0700239 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700240 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800241 ASSERT_EQ(touchedToken, mOnPointerDownToken);
242 mOnPointerDownToken.clear();
243 }
244
245 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700246 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800247 ASSERT_TRUE(mOnPointerDownToken == nullptr)
248 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700249 }
250
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700251 // This function must be called soon after the expected ANR timer starts,
252 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500253 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700254 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500255 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800256 std::unique_lock lock(mLock);
257 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500258 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800259 ASSERT_NO_FATAL_FAILURE(
260 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500261 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700262 }
263
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000264 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800265 const sp<WindowInfoHandle>& window) {
266 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
267 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
268 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500269 }
270
Prabir Pradhanedd96402022-02-15 01:46:16 -0800271 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
272 const sp<IBinder>& expectedToken,
273 int32_t expectedPid) {
274 std::unique_lock lock(mLock);
275 android::base::ScopedLockAssertion assumeLocked(mLock);
276 AnrResult result;
277 ASSERT_NO_FATAL_FAILURE(result =
278 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
279 const auto& [token, pid] = result;
280 ASSERT_EQ(expectedToken, token);
281 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500282 }
283
Prabir Pradhanedd96402022-02-15 01:46:16 -0800284 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000285 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500286 std::unique_lock lock(mLock);
287 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800288 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
289 const auto& [token, _] = result;
290 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000291 }
292
Prabir Pradhanedd96402022-02-15 01:46:16 -0800293 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
294 int32_t expectedPid) {
295 std::unique_lock lock(mLock);
296 android::base::ScopedLockAssertion assumeLocked(mLock);
297 AnrResult result;
298 ASSERT_NO_FATAL_FAILURE(
299 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
300 const auto& [token, pid] = result;
301 ASSERT_EQ(expectedToken, token);
302 ASSERT_EQ(expectedPid, pid);
303 }
304
305 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000306 sp<IBinder> getResponsiveWindowToken() {
307 std::unique_lock lock(mLock);
308 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800309 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
310 const auto& [token, _] = result;
311 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700312 }
313
314 void assertNotifyAnrWasNotCalled() {
315 std::scoped_lock lock(mLock);
316 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800317 ASSERT_TRUE(mAnrWindows.empty());
318 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500319 << "ANR was not called, but please also consume the 'connection is responsive' "
320 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700321 }
322
Garfield Tan1c7bc862020-01-28 13:24:04 -0800323 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
324 mConfig.keyRepeatTimeout = timeout;
325 mConfig.keyRepeatDelay = delay;
326 }
327
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000328 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800329 std::unique_lock lock(mLock);
330 base::ScopedLockAssertion assumeLocked(mLock);
331
332 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
333 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000334 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800335 enabled;
336 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000337 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
338 << ") to be called.";
339 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800340 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000341 auto request = *mPointerCaptureRequest;
342 mPointerCaptureRequest.reset();
343 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800344 }
345
346 void assertSetPointerCaptureNotCalled() {
347 std::unique_lock lock(mLock);
348 base::ScopedLockAssertion assumeLocked(mLock);
349
350 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000351 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800352 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000353 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800354 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000355 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800356 }
357
arthurhungf452d0b2021-01-06 00:19:52 +0800358 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
359 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800360 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800361 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800362 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800363 }
364
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800365 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
366 std::unique_lock lock(mLock);
367 base::ScopedLockAssertion assumeLocked(mLock);
368 std::optional<sp<IBinder>> receivedToken =
369 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
370 mNotifyInputChannelBroken);
371 ASSERT_TRUE(receivedToken.has_value());
372 ASSERT_EQ(token, *receivedToken);
373 }
374
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800375 /**
376 * Set policy timeout. A value of zero means next key will not be intercepted.
377 */
378 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
379 mInterceptKeyTimeout = timeout;
380 }
381
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700383 std::mutex mLock;
384 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
385 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
386 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
387 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800388
Prabir Pradhan99987712020-11-10 18:43:05 -0800389 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000390
391 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800392
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700393 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700394 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800395 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
396 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700397 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800398 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
399 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700400
arthurhungf452d0b2021-01-06 00:19:52 +0800401 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800402 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800403
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800404 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
405
Prabir Pradhanedd96402022-02-15 01:46:16 -0800406 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
407 // for a specific container to become non-empty. When the container is non-empty, return the
408 // first entry from the container and erase it.
409 template <class T>
410 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
411 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
412 // If there is an ANR, Dispatcher won't be idle because there are still events
413 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
414 // before checking if ANR was called.
415 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
416 // to provide it some time to act. 100ms seems reasonable.
417 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
418 const std::chrono::time_point start = std::chrono::steady_clock::now();
419 std::optional<T> token =
420 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
421 if (!token.has_value()) {
422 ADD_FAILURE() << "Did not receive the ANR callback";
423 return {};
424 }
425
426 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
427 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
428 // the dispatcher started counting before this function was called
429 if (std::chrono::abs(timeout - waited) > 100ms) {
430 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
431 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
432 << "ms, but waited "
433 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
434 << "ms instead";
435 }
436 return *token;
437 }
438
439 template <class T>
440 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
441 std::queue<T>& storage,
442 std::unique_lock<std::mutex>& lock,
443 std::condition_variable& condition)
444 REQUIRES(mLock) {
445 condition.wait_for(lock, timeout,
446 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
447 if (storage.empty()) {
448 ADD_FAILURE() << "Did not receive the expected callback";
449 return std::nullopt;
450 }
451 T item = storage.front();
452 storage.pop();
453 return std::make_optional(item);
454 }
455
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600456 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700457 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800458 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 }
460
Prabir Pradhanedd96402022-02-15 01:46:16 -0800461 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
462 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700463 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800464 ASSERT_TRUE(pid.has_value());
465 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700466 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500467 }
468
Prabir Pradhanedd96402022-02-15 01:46:16 -0800469 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
470 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500471 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800472 ASSERT_TRUE(pid.has_value());
473 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500474 mNotifyAnr.notify_all();
475 }
476
477 void notifyNoFocusedWindowAnr(
478 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
479 std::scoped_lock lock(mLock);
480 mAnrApplications.push(applicationHandle);
481 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 }
483
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800484 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
485 std::scoped_lock lock(mLock);
486 mBrokenInputChannels.push(connectionToken);
487 mNotifyInputChannelBroken.notify_all();
488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600490 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700491
Chris Yef59a2f42020-10-16 12:55:26 -0700492 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
493 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
494 const std::vector<float>& values) override {}
495
496 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
497 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000498
Chris Yefb552902021-02-03 17:18:37 -0800499 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
500
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600501 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 *outConfig = mConfig;
503 }
504
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600505 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700506 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800507 switch (inputEvent->getType()) {
508 case AINPUT_EVENT_TYPE_KEY: {
509 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800510 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800511 break;
512 }
513
514 case AINPUT_EVENT_TYPE_MOTION: {
515 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800516 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800517 break;
518 }
519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 return true;
521 }
522
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800523 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
524 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
525 // Clear intercept state when we handled the event.
526 mInterceptKeyTimeout = 0ms;
527 }
528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600530 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600532 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800533 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
534 // Clear intercept state so we could dispatch the event in next wake.
535 mInterceptKeyTimeout = 0ms;
536 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 }
538
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600539 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 return false;
541 }
542
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600543 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
544 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700545 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800546 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
547 * essentially a passthrough for notifySwitch.
548 */
Harry Cutts33476232023-01-30 19:57:29 +0000549 mLastNotifySwitch = NotifySwitchArgs(/*id=*/1, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 }
551
Sean Stoutb4e0a592021-02-23 07:34:53 -0800552 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600554 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700555 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700556 mOnPointerDownToken = newToken;
557 }
558
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000559 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800560 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000561 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800562 mPointerCaptureChangedCondition.notify_all();
563 }
564
arthurhungf452d0b2021-01-06 00:19:52 +0800565 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
566 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800567 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800568 mDropTargetWindowToken = token;
569 }
570
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700571 void assertFilterInputEventWasCalledInternal(
572 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700573 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800574 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700575 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800576 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578};
579
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580// --- InputDispatcherTest ---
581
582class InputDispatcherTest : public testing::Test {
583protected:
584 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700585 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000587 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700588 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800589 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800590 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000591 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700592 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 }
594
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000595 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700598 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700600
601 /**
602 * Used for debugging when writing the test
603 */
604 void dumpDispatcherState() {
605 std::string dump;
606 mDispatcher->dump(dump);
607 std::stringstream ss(dump);
608 std::string to;
609
610 while (std::getline(ss, to, '\n')) {
611 ALOGE("%s", to.c_str());
612 }
613 }
Vishnu Nair958da932020-08-21 17:12:37 -0700614
chaviw3277faf2021-05-19 16:45:23 -0500615 void setFocusedWindow(const sp<WindowInfoHandle>& window,
616 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700617 FocusRequest request;
618 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000619 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700620 if (focusedWindow) {
621 request.focusedToken = focusedWindow->getToken();
622 }
623 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
624 request.displayId = window->getInfo()->displayId;
625 mDispatcher->setFocusedWindow(request);
626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627};
628
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
630 KeyEvent event;
631
632 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800633 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
634 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600635 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
636 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800637 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000638 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000639 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 << "Should reject key events with undefined action.";
641
642 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800643 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
644 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600645 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800646 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000647 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000648 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 << "Should reject key events with ACTION_MULTIPLE.";
650}
651
652TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
653 MotionEvent event;
654 PointerProperties pointerProperties[MAX_POINTERS + 1];
655 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800656 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 pointerProperties[i].clear();
658 pointerProperties[i].id = i;
659 pointerCoords[i].clear();
660 }
661
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800662 // Some constants commonly used below
663 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
664 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
665 constexpr int32_t metaState = AMETA_NONE;
666 constexpr MotionClassification classification = MotionClassification::NONE;
667
chaviw9eaa22c2020-07-01 16:21:27 -0700668 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800670 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700671 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
672 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700673 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
674 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700675 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800676 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000677 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000678 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 << "Should reject motion events with undefined action.";
680
681 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800682 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800683 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
684 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
685 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
686 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500687 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800688 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000689 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000690 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 << "Should reject motion events with pointer down index too large.";
692
Garfield Tanfbe732e2020-01-24 11:26:14 -0800693 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700694 AMOTION_EVENT_ACTION_POINTER_DOWN |
695 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700696 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
697 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700698 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500699 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800700 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000701 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000702 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 << "Should reject motion events with pointer down index too small.";
704
705 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800706 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800707 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
708 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
709 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
710 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500711 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800712 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000713 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000714 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 << "Should reject motion events with pointer up index too large.";
716
Garfield Tanfbe732e2020-01-24 11:26:14 -0800717 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700718 AMOTION_EVENT_ACTION_POINTER_UP |
719 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700720 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
721 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700722 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500723 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800724 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000725 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000726 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 << "Should reject motion events with pointer up index too small.";
728
729 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800730 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
731 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700732 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700733 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
734 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700735 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800736 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000737 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000738 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 << "Should reject motion events with 0 pointers.";
740
Garfield Tanfbe732e2020-01-24 11:26:14 -0800741 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
742 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700743 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700744 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
745 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700746 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800747 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000748 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000749 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 << "Should reject motion events with more than MAX_POINTERS pointers.";
751
752 // Rejects motion events with invalid pointer ids.
753 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800754 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
755 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700756 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700757 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
758 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700759 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800760 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000761 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000762 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 << "Should reject motion events with pointer ids less than 0.";
764
765 pointerProperties[0].id = MAX_POINTER_ID + 1;
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*/ 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 pointer ids greater than MAX_POINTER_ID.";
776
777 // Rejects motion events with duplicate pointer ids.
778 pointerProperties[0].id = 1;
779 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800780 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
781 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700782 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700783 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
784 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700785 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800786 ASSERT_EQ(InputEventInjectionResult::FAILED,
Harry Cutts33476232023-01-30 19:57:29 +0000787 mDispatcher->injectInputEvent(&event, /*targetUid=*/{}, InputEventInjectionSync::NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000788 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 << "Should reject motion events with duplicate pointer ids.";
790}
791
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800792/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
793
794TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
795 constexpr nsecs_t eventTime = 20;
Harry Cutts33476232023-01-30 19:57:29 +0000796 NotifyConfigurationChangedArgs args(/*id=*/10, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800797 mDispatcher->notifyConfigurationChanged(&args);
798 ASSERT_TRUE(mDispatcher->waitForIdle());
799
800 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
801}
802
803TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Harry Cutts33476232023-01-30 19:57:29 +0000804 NotifySwitchArgs args(/*id=*/10, /*eventTime=*/20, /*policyFlags=*/0, /*switchValues=*/1,
805 /*switchMask=*/2);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800806 mDispatcher->notifySwitch(&args);
807
808 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
809 args.policyFlags |= POLICY_FLAG_TRUSTED;
810 mFakePolicy->assertNotifySwitchWasCalled(args);
811}
812
Arthur Hungb92218b2018-08-14 12:00:21 +0800813// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700814static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700815// Default input dispatching timeout if there is no focused application or paused window
816// from which to determine an appropriate dispatching timeout.
817static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
818 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
819 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800820
821class FakeApplicationHandle : public InputApplicationHandle {
822public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700823 FakeApplicationHandle() {
824 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700825 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500826 mInfo.dispatchingTimeoutMillis =
827 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700828 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800829 virtual ~FakeApplicationHandle() {}
830
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000831 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700832
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500833 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
834 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700835 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800836};
837
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800838class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800839public:
Garfield Tan15601662020-09-22 15:32:38 -0700840 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800841 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700842 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800843 }
844
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800845 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700846 InputEvent* event;
847 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
848 if (!consumeSeq) {
849 return nullptr;
850 }
851 finishEvent(*consumeSeq);
852 return event;
853 }
854
855 /**
856 * Receive an event without acknowledging it.
857 * Return the sequence number that could later be used to send finished signal.
858 */
859 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800860 uint32_t consumeSeq;
861 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800862
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800863 std::chrono::time_point start = std::chrono::steady_clock::now();
864 status_t status = WOULD_BLOCK;
865 while (status == WOULD_BLOCK) {
Harry Cutts33476232023-01-30 19:57:29 +0000866 status = mConsumer->consume(&mEventFactory, /*consumeBatches=*/true, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800867 &event);
868 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
869 if (elapsed > 100ms) {
870 break;
871 }
872 }
873
874 if (status == WOULD_BLOCK) {
875 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700876 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800877 }
878
879 if (status != OK) {
880 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700881 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800882 }
883 if (event == nullptr) {
884 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700885 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800886 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700887 if (outEvent != nullptr) {
888 *outEvent = event;
889 }
890 return consumeSeq;
891 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800892
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700893 /**
894 * To be used together with "receiveEvent" to complete the consumption of an event.
895 */
896 void finishEvent(uint32_t consumeSeq) {
897 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
898 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800899 }
900
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000901 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
902 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
903 ASSERT_EQ(OK, status);
904 }
905
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000906 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
907 std::optional<int32_t> expectedDisplayId,
908 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800909 InputEvent* event = consume();
910
911 ASSERT_NE(nullptr, event) << mName.c_str()
912 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800913 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800915 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800916
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000917 if (expectedDisplayId.has_value()) {
918 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
919 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800920
Tiger Huang8664f8c2018-10-11 19:14:35 +0800921 switch (expectedEventType) {
922 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800923 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
924 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000925 if (expectedFlags.has_value()) {
926 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
927 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800928 break;
929 }
930 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800931 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000932 assertMotionAction(expectedAction, motionEvent.getAction());
933
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000934 if (expectedFlags.has_value()) {
935 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
936 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800937 break;
938 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100939 case AINPUT_EVENT_TYPE_FOCUS: {
940 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
941 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800942 case AINPUT_EVENT_TYPE_CAPTURE: {
943 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
944 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000945 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
946 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
947 }
arthurhungb89ccb02020-12-30 16:19:01 +0800948 case AINPUT_EVENT_TYPE_DRAG: {
949 FAIL() << "Use 'consumeDragEvent' for DRAG events";
950 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800951 default: {
952 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
953 }
954 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800955 }
956
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -0800957 MotionEvent* consumeMotion() {
958 InputEvent* event = consume();
959
960 if (event == nullptr) {
961 ADD_FAILURE() << mName << ": expected a MotionEvent, but didn't get one.";
962 return nullptr;
963 }
964
965 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
966 ADD_FAILURE() << mName << " expected a MotionEvent, got "
967 << inputEventTypeToString(event->getType()) << " event";
968 return nullptr;
969 }
970 return static_cast<MotionEvent*>(event);
971 }
972
973 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
974 MotionEvent* motionEvent = consumeMotion();
975 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
976 ASSERT_THAT(*motionEvent, matcher);
977 }
978
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100979 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
980 InputEvent* event = consume();
981 ASSERT_NE(nullptr, event) << mName.c_str()
982 << ": consumer should have returned non-NULL event.";
983 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
984 << "Got " << inputEventTypeToString(event->getType())
985 << " event instead of FOCUS event";
986
987 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
988 << mName.c_str() << ": event displayId should always be NONE.";
989
990 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
991 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100992 }
993
Prabir Pradhan99987712020-11-10 18:43:05 -0800994 void consumeCaptureEvent(bool hasCapture) {
995 const InputEvent* event = consume();
996 ASSERT_NE(nullptr, event) << mName.c_str()
997 << ": consumer should have returned non-NULL event.";
998 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
999 << "Got " << inputEventTypeToString(event->getType())
1000 << " event instead of CAPTURE event";
1001
1002 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1003 << mName.c_str() << ": event displayId should always be NONE.";
1004
1005 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
1006 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
1007 }
1008
arthurhungb89ccb02020-12-30 16:19:01 +08001009 void consumeDragEvent(bool isExiting, float x, float y) {
1010 const InputEvent* event = consume();
1011 ASSERT_NE(nullptr, event) << mName.c_str()
1012 << ": consumer should have returned non-NULL event.";
1013 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
1014 << "Got " << inputEventTypeToString(event->getType())
1015 << " event instead of DRAG event";
1016
1017 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1018 << mName.c_str() << ": event displayId should always be NONE.";
1019
1020 const auto& dragEvent = static_cast<const DragEvent&>(*event);
1021 EXPECT_EQ(isExiting, dragEvent.isExiting());
1022 EXPECT_EQ(x, dragEvent.getX());
1023 EXPECT_EQ(y, dragEvent.getY());
1024 }
1025
Antonio Kantekf16f2832021-09-28 04:39:20 +00001026 void consumeTouchModeEvent(bool inTouchMode) {
1027 const InputEvent* event = consume();
1028 ASSERT_NE(nullptr, event) << mName.c_str()
1029 << ": consumer should have returned non-NULL event.";
1030 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
1031 << "Got " << inputEventTypeToString(event->getType())
1032 << " event instead of TOUCH_MODE event";
1033
1034 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
1035 << mName.c_str() << ": event displayId should always be NONE.";
1036 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
1037 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
1038 }
1039
chaviwd1c23182019-12-20 18:44:56 -08001040 void assertNoEvents() {
1041 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001042 if (event == nullptr) {
1043 return;
1044 }
1045 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
1046 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
1047 ADD_FAILURE() << "Received key event "
1048 << KeyEvent::actionToString(keyEvent.getAction());
1049 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
1050 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1051 ADD_FAILURE() << "Received motion event "
1052 << MotionEvent::actionToString(motionEvent.getAction());
1053 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
1054 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
1055 ADD_FAILURE() << "Received focus event, hasFocus = "
1056 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -08001057 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
1058 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
1059 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
1060 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +00001061 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
1062 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
1063 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
1064 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001065 }
1066 FAIL() << mName.c_str()
1067 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -08001068 }
1069
1070 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1071
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001072 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1073
chaviwd1c23182019-12-20 18:44:56 -08001074protected:
1075 std::unique_ptr<InputConsumer> mConsumer;
1076 PreallocatedInputEventFactory mEventFactory;
1077
1078 std::string mName;
1079};
1080
chaviw3277faf2021-05-19 16:45:23 -05001081class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001082public:
1083 static const int32_t WIDTH = 600;
1084 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001085
Chris Yea209fde2020-07-22 13:54:51 -07001086 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001087 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001088 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001089 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001090 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001091 base::Result<std::unique_ptr<InputChannel>> channel =
1092 dispatcher->createInputChannel(name);
1093 token = (*channel)->getConnectionToken();
1094 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001095 }
1096
1097 inputApplicationHandle->updateInfo();
1098 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1099
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001100 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001101 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001102 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001103 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001104 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001105 mInfo.frameLeft = 0;
1106 mInfo.frameTop = 0;
1107 mInfo.frameRight = WIDTH;
1108 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001109 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001110 mInfo.globalScaleFactor = 1.0;
1111 mInfo.touchableRegion.clear();
1112 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001113 mInfo.ownerPid = WINDOW_PID;
1114 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001115 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001116 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001117 }
1118
Arthur Hungabbb9d82021-09-01 14:52:30 +00001119 sp<FakeWindowHandle> clone(
1120 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001121 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001122 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001123 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1124 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001125 return handle;
1126 }
1127
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001128 void setTouchable(bool touchable) {
1129 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1130 }
chaviwd1c23182019-12-20 18:44:56 -08001131
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001132 void setFocusable(bool focusable) {
1133 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1134 }
1135
1136 void setVisible(bool visible) {
1137 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1138 }
Vishnu Nair958da932020-08-21 17:12:37 -07001139
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001140 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001141 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001142 }
1143
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001144 void setPaused(bool paused) {
1145 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1146 }
1147
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001148 void setPreventSplitting(bool preventSplitting) {
1149 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001150 }
1151
1152 void setSlippery(bool slippery) {
1153 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1154 }
1155
1156 void setWatchOutsideTouch(bool watchOutside) {
1157 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1158 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001159
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001160 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1161
1162 void setInterceptsStylus(bool interceptsStylus) {
1163 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1164 }
1165
1166 void setDropInput(bool dropInput) {
1167 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1168 }
1169
1170 void setDropInputIfObscured(bool dropInputIfObscured) {
1171 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1172 }
1173
1174 void setNoInputChannel(bool noInputChannel) {
1175 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1176 }
1177
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001178 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1179
chaviw3277faf2021-05-19 16:45:23 -05001180 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001181
Bernardo Rufino7393d172021-02-26 13:56:11 +00001182 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1183
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001184 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001185 mInfo.frameLeft = frame.left;
1186 mInfo.frameTop = frame.top;
1187 mInfo.frameRight = frame.right;
1188 mInfo.frameBottom = frame.bottom;
1189 mInfo.touchableRegion.clear();
1190 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001191
1192 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1193 ui::Transform translate;
1194 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1195 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001196 }
1197
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001198 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1199
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001200 void setIsWallpaper(bool isWallpaper) {
1201 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1202 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001203
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001204 void setDupTouchToWallpaper(bool hasWallpaper) {
1205 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1206 }
chaviwd1c23182019-12-20 18:44:56 -08001207
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001208 void setTrustedOverlay(bool trustedOverlay) {
1209 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1210 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001211
chaviw9eaa22c2020-07-01 16:21:27 -07001212 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1213 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1214 }
1215
1216 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001217
yunho.shinf4a80b82020-11-16 21:13:57 +09001218 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1219
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001220 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1221 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1222 expectedFlags);
1223 }
1224
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001225 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1226 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1227 }
1228
Svet Ganov5d3bc372020-01-26 23:11:07 -08001229 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001230 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001231 consumeMotionEvent(AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(expectedDisplayId),
1232 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001233 }
1234
1235 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001236 int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08001237 consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
1238 WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
Svet Ganov5d3bc372020-01-26 23:11:07 -08001239 }
1240
1241 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001242 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001243 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1244 }
1245
1246 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1247 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001248 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1249 expectedFlags);
1250 }
1251
Svet Ganov5d3bc372020-01-26 23:11:07 -08001252 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001253 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1254 int32_t expectedFlags = 0) {
1255 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1256 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001257 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1258 }
1259
1260 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001261 int32_t expectedFlags = 0) {
1262 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1263 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001264 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1265 }
1266
1267 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001268 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001269 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1270 expectedFlags);
1271 }
1272
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001273 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1274 int32_t expectedFlags = 0) {
1275 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1276 expectedFlags);
1277 }
1278
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001279 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1280 int32_t expectedFlags = 0) {
1281 InputEvent* event = consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08001282 ASSERT_NE(nullptr, event);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001283 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1284 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1285 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1286 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1287 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1288 }
1289
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001290 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1291 ASSERT_NE(mInputReceiver, nullptr)
1292 << "Cannot consume events from a window with no receiver";
1293 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1294 }
1295
Prabir Pradhan99987712020-11-10 18:43:05 -08001296 void consumeCaptureEvent(bool hasCapture) {
1297 ASSERT_NE(mInputReceiver, nullptr)
1298 << "Cannot consume events from a window with no receiver";
1299 mInputReceiver->consumeCaptureEvent(hasCapture);
1300 }
1301
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001302 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1303 MotionEvent* motionEvent = consumeMotion();
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08001304 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event, but expected " << matcher;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001305 ASSERT_THAT(*motionEvent, matcher);
1306 }
1307
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001308 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1309 std::optional<int32_t> expectedDisplayId,
1310 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001311 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1312 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1313 expectedFlags);
1314 }
1315
arthurhungb89ccb02020-12-30 16:19:01 +08001316 void consumeDragEvent(bool isExiting, float x, float y) {
1317 mInputReceiver->consumeDragEvent(isExiting, x, y);
1318 }
1319
Antonio Kantekf16f2832021-09-28 04:39:20 +00001320 void consumeTouchModeEvent(bool inTouchMode) {
1321 ASSERT_NE(mInputReceiver, nullptr)
1322 << "Cannot consume events from a window with no receiver";
1323 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1324 }
1325
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001326 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001327 if (mInputReceiver == nullptr) {
1328 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1329 return std::nullopt;
1330 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001331 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001332 }
1333
1334 void finishEvent(uint32_t sequenceNum) {
1335 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1336 mInputReceiver->finishEvent(sequenceNum);
1337 }
1338
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001339 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1340 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1341 mInputReceiver->sendTimeline(inputEventId, timeline);
1342 }
1343
chaviwaf87b3e2019-10-01 16:59:28 -07001344 InputEvent* consume() {
1345 if (mInputReceiver == nullptr) {
1346 return nullptr;
1347 }
1348 return mInputReceiver->consume();
1349 }
1350
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001351 MotionEvent* consumeMotion() {
1352 InputEvent* event = consume();
1353 if (event == nullptr) {
1354 ADD_FAILURE() << "Consume failed : no event";
1355 return nullptr;
1356 }
1357 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1358 ADD_FAILURE() << "Instead of motion event, got "
1359 << inputEventTypeToString(event->getType());
1360 return nullptr;
1361 }
1362 return static_cast<MotionEvent*>(event);
1363 }
1364
Arthur Hungb92218b2018-08-14 12:00:21 +08001365 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001366 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001367 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001368 return; // Can't receive events if the window does not have input channel
1369 }
1370 ASSERT_NE(nullptr, mInputReceiver)
1371 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001372 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001373 }
1374
chaviwaf87b3e2019-10-01 16:59:28 -07001375 sp<IBinder> getToken() { return mInfo.token; }
1376
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001377 const std::string& getName() { return mName; }
1378
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001379 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1380 mInfo.ownerPid = ownerPid;
1381 mInfo.ownerUid = ownerUid;
1382 }
1383
Prabir Pradhanedd96402022-02-15 01:46:16 -08001384 int32_t getPid() const { return mInfo.ownerPid; }
1385
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001386 void destroyReceiver() { mInputReceiver = nullptr; }
1387
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001388 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1389
chaviwd1c23182019-12-20 18:44:56 -08001390private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001391 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001392 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001393 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001394};
1395
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001396std::atomic<int32_t> FakeWindowHandle::sId{1};
1397
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001398static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001399 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001400 int32_t displayId = ADISPLAY_ID_NONE,
1401 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001402 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001403 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1404 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001405 KeyEvent event;
1406 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1407
1408 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001409 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Harry Cutts33476232023-01-30 19:57:29 +00001410 INVALID_HMAC, action, /*flags=*/0, AKEYCODE_A, KEY_A, AMETA_NONE, repeatCount,
1411 currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001412
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001413 if (!allowKeyRepeat) {
1414 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1415 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001416 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001417 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001418}
1419
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001420static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001422 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001423}
1424
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001425// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1426// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1427// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001428static InputEventInjectionResult injectKeyDownNoRepeat(
1429 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001430 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, displayId,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001431 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
Harry Cutts33476232023-01-30 19:57:29 +00001432 /*allowKeyRepeat=*/false);
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001433}
1434
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001435static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001436 int32_t displayId = ADISPLAY_ID_NONE) {
Harry Cutts33476232023-01-30 19:57:29 +00001437 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /*repeatCount=*/0, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001438}
1439
Garfield Tandf26e862020-07-01 20:18:19 -07001440class PointerBuilder {
1441public:
1442 PointerBuilder(int32_t id, int32_t toolType) {
1443 mProperties.clear();
1444 mProperties.id = id;
1445 mProperties.toolType = toolType;
1446 mCoords.clear();
1447 }
1448
1449 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1450
1451 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1452
1453 PointerBuilder& axis(int32_t axis, float value) {
1454 mCoords.setAxisValue(axis, value);
1455 return *this;
1456 }
1457
1458 PointerProperties buildProperties() const { return mProperties; }
1459
1460 PointerCoords buildCoords() const { return mCoords; }
1461
1462private:
1463 PointerProperties mProperties;
1464 PointerCoords mCoords;
1465};
1466
1467class MotionEventBuilder {
1468public:
1469 MotionEventBuilder(int32_t action, int32_t source) {
1470 mAction = action;
1471 mSource = source;
1472 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001473 mDownTime = mEventTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001474 }
1475
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001476 MotionEventBuilder& deviceId(int32_t deviceId) {
1477 mDeviceId = deviceId;
1478 return *this;
1479 }
1480
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001481 MotionEventBuilder& downTime(nsecs_t downTime) {
1482 mDownTime = downTime;
1483 return *this;
1484 }
1485
Garfield Tandf26e862020-07-01 20:18:19 -07001486 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1487 mEventTime = eventTime;
1488 return *this;
1489 }
1490
1491 MotionEventBuilder& displayId(int32_t displayId) {
1492 mDisplayId = displayId;
1493 return *this;
1494 }
1495
1496 MotionEventBuilder& actionButton(int32_t actionButton) {
1497 mActionButton = actionButton;
1498 return *this;
1499 }
1500
arthurhung6d4bed92021-03-17 11:59:33 +08001501 MotionEventBuilder& buttonState(int32_t buttonState) {
1502 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001503 return *this;
1504 }
1505
1506 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1507 mRawXCursorPosition = rawXCursorPosition;
1508 return *this;
1509 }
1510
1511 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1512 mRawYCursorPosition = rawYCursorPosition;
1513 return *this;
1514 }
1515
1516 MotionEventBuilder& pointer(PointerBuilder pointer) {
1517 mPointers.push_back(pointer);
1518 return *this;
1519 }
1520
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001521 MotionEventBuilder& addFlag(uint32_t flags) {
1522 mFlags |= flags;
1523 return *this;
1524 }
1525
Garfield Tandf26e862020-07-01 20:18:19 -07001526 MotionEvent build() {
1527 std::vector<PointerProperties> pointerProperties;
1528 std::vector<PointerCoords> pointerCoords;
1529 for (const PointerBuilder& pointer : mPointers) {
1530 pointerProperties.push_back(pointer.buildProperties());
1531 pointerCoords.push_back(pointer.buildCoords());
1532 }
1533
1534 // Set mouse cursor position for the most common cases to avoid boilerplate.
1535 if (mSource == AINPUT_SOURCE_MOUSE &&
1536 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1537 mPointers.size() == 1) {
1538 mRawXCursorPosition = pointerCoords[0].getX();
1539 mRawYCursorPosition = pointerCoords[0].getY();
1540 }
1541
1542 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001543 ui::Transform identityTransform;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001544 event.initialize(InputEvent::nextId(), mDeviceId, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001545 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001546 mButtonState, MotionClassification::NONE, identityTransform,
1547 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001548 mRawYCursorPosition, identityTransform, mDownTime, mEventTime,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001549 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001550
1551 return event;
1552 }
1553
1554private:
1555 int32_t mAction;
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08001556 int32_t mDeviceId = DEVICE_ID;
Garfield Tandf26e862020-07-01 20:18:19 -07001557 int32_t mSource;
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08001558 nsecs_t mDownTime;
Garfield Tandf26e862020-07-01 20:18:19 -07001559 nsecs_t mEventTime;
1560 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1561 int32_t mActionButton{0};
1562 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001563 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001564 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1565 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1566
1567 std::vector<PointerBuilder> mPointers;
1568};
1569
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001571 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001572 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001573 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1574 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1575 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1576 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001577}
1578
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001579static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001580 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001581 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001582 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001583 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1584 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001586 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1587 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001588 MotionEvent event = MotionEventBuilder(action, source)
1589 .displayId(displayId)
1590 .eventTime(eventTime)
1591 .rawXCursorPosition(cursorPosition.x)
1592 .rawYCursorPosition(cursorPosition.y)
Harry Cutts33476232023-01-30 19:57:29 +00001593 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001594 .x(position.x)
1595 .y(position.y))
1596 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001597
1598 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001599 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1600 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001601}
1602
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001603static InputEventInjectionResult injectMotionDown(
1604 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1605 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001606 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001607}
1608
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001609static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001610 int32_t source, int32_t displayId,
1611 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001612 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001613}
1614
Jackal Guof9696682018-10-05 12:23:23 +08001615static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1616 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1617 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001618 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001619 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1620 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001621
1622 return args;
1623}
1624
chaviwd1c23182019-12-20 18:44:56 -08001625static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1626 const std::vector<PointF>& points) {
1627 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001628 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1629 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1630 }
1631
chaviwd1c23182019-12-20 18:44:56 -08001632 PointerProperties pointerProperties[pointerCount];
1633 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001634
chaviwd1c23182019-12-20 18:44:56 -08001635 for (size_t i = 0; i < pointerCount; i++) {
1636 pointerProperties[i].clear();
1637 pointerProperties[i].id = i;
1638 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001639
chaviwd1c23182019-12-20 18:44:56 -08001640 pointerCoords[i].clear();
1641 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1642 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1643 }
Jackal Guof9696682018-10-05 12:23:23 +08001644
1645 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1646 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001647 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001648 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1649 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001650 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1651 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1653 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001654
1655 return args;
1656}
1657
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001658static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1659 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1660}
1661
chaviwd1c23182019-12-20 18:44:56 -08001662static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1663 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1664}
1665
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001666static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1667 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001668 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001669}
1670
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001671/**
1672 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1673 * broken channel.
1674 */
1675TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1676 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1677 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001678 sp<FakeWindowHandle>::make(application, mDispatcher,
1679 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001680
1681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1682
1683 // Window closes its channel, but the window remains.
1684 window->destroyReceiver();
1685 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1686}
1687
Arthur Hungb92218b2018-08-14 12:00:21 +08001688TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001690 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1691 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001692
Arthur Hung72d8dc32020-03-28 00:48:39 +00001693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1695 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1696 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001697
1698 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001699 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001700}
1701
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001702TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1703 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001704 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1705 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001706
1707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1708 // Inject a MotionEvent to an unknown display.
1709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1710 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1712
1713 // Window should receive motion event.
1714 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1715}
1716
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001717/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001718 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001719 * This test serves as a sanity check for the next test, where setInputWindows is
1720 * called twice.
1721 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001722TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001723 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001724 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1725 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001726 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001727
1728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001730 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1731 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001733
1734 // Window should receive motion event.
1735 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1736}
1737
1738/**
1739 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001740 */
1741TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001742 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001743 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1744 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001745 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001746
1747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001750 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1751 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001752 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001753
1754 // Window should receive motion event.
1755 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1756}
1757
Arthur Hungb92218b2018-08-14 12:00:21 +08001758// The foreground window should receive the first touch down event.
1759TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001761 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001762 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001763 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001764 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001765
Arthur Hung72d8dc32020-03-28 00:48:39 +00001766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1768 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001770
1771 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001772 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001773 windowSecond->assertNoEvents();
1774}
1775
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776/**
1777 * Two windows: A top window, and a wallpaper behind the window.
1778 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1779 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001780 * 1. foregroundWindow <-- dup touch to wallpaper
1781 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001782 */
1783TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1784 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1785 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001786 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001787 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001788 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001789 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001790 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001791
1792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1795 {100, 200}))
1796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1797
1798 // Both foreground window and its wallpaper should receive the touch down
1799 foregroundWindow->consumeMotionDown();
1800 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1801
1802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1803 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1804 ADISPLAY_ID_DEFAULT, {110, 200}))
1805 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1806
1807 foregroundWindow->consumeMotionMove();
1808 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1809
1810 // Now the foreground window goes away, but the wallpaper stays
1811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1812 foregroundWindow->consumeMotionCancel();
1813 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1814 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1815}
1816
1817/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001818 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1819 * with the following differences:
1820 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1821 * clean up the connection.
1822 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1823 * Ensure that there's no crash in the dispatcher.
1824 */
1825TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1826 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1827 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001828 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001829 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001830 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001831 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001832 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001833
1834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1836 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1837 {100, 200}))
1838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1839
1840 // Both foreground window and its wallpaper should receive the touch down
1841 foregroundWindow->consumeMotionDown();
1842 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1843
1844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1845 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1846 ADISPLAY_ID_DEFAULT, {110, 200}))
1847 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1848
1849 foregroundWindow->consumeMotionMove();
1850 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1851
1852 // Wallpaper closes its channel, but the window remains.
1853 wallpaperWindow->destroyReceiver();
1854 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1855
1856 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1857 // is no longer valid.
1858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1859 foregroundWindow->consumeMotionCancel();
1860}
1861
Arthur Hungc539dbb2022-12-08 07:45:36 +00001862class ShouldSplitTouchFixture : public InputDispatcherTest,
1863 public ::testing::WithParamInterface<bool> {};
1864INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1865 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001866/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001867 * A single window that receives touch (on top), and a wallpaper window underneath it.
1868 * The top window gets a multitouch gesture.
1869 * Ensure that wallpaper gets the same gesture.
1870 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00001871TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00001873 sp<FakeWindowHandle> foregroundWindow =
1874 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1875 foregroundWindow->setDupTouchToWallpaper(true);
1876 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001877
1878 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001879 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001880 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001881
Arthur Hungc539dbb2022-12-08 07:45:36 +00001882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001883
1884 // Touch down on top window
1885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1886 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1887 {100, 100}))
1888 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1889
1890 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00001891 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001892 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1893
1894 // Second finger down on the top window
1895 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001896 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001897 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00001898 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1899 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001900 .build();
1901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1902 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1903 InputEventInjectionSync::WAIT_FOR_RESULT))
1904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1905
Harry Cutts33476232023-01-30 19:57:29 +00001906 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
1907 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001908 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00001909
1910 const MotionEvent secondFingerUpEvent =
1911 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1912 .displayId(ADISPLAY_ID_DEFAULT)
1913 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00001914 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1915 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00001916 .build();
1917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1918 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1919 InputEventInjectionSync::WAIT_FOR_RESULT))
1920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1921 foregroundWindow->consumeMotionPointerUp(0);
1922 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1923
1924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1925 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1926 {100, 100}))
1927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1928 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1929 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001930}
1931
1932/**
1933 * Two windows: a window on the left and window on the right.
1934 * A third window, wallpaper, is behind both windows, and spans both top windows.
1935 * The first touch down goes to the left window. A second pointer touches down on the right window.
1936 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1937 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1938 * ACTION_POINTER_DOWN(1).
1939 */
1940TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1941 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1942 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001943 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001944 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001945 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001946
1947 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001948 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001949 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001950 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001951
1952 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001953 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001954 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001955 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001956
1957 mDispatcher->setInputWindows(
1958 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1959
1960 // Touch down on left window
1961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1962 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1963 {100, 100}))
1964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1965
1966 // Both foreground window and its wallpaper should receive the touch down
1967 leftWindow->consumeMotionDown();
1968 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1969
1970 // Second finger down on the right window
1971 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001972 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001973 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00001974 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
1975 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001976 .build();
1977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1978 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1979 InputEventInjectionSync::WAIT_FOR_RESULT))
1980 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1981
1982 leftWindow->consumeMotionMove();
1983 // Since the touch is split, right window gets ACTION_DOWN
1984 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00001985 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001986 expectedWallpaperFlags);
1987
1988 // Now, leftWindow, which received the first finger, disappears.
1989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1990 leftWindow->consumeMotionCancel();
1991 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1992 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1993
1994 // The pointer that's still down on the right window moves, and goes to the right window only.
1995 // As far as the dispatcher's concerned though, both pointers are still present.
1996 const MotionEvent secondFingerMoveEvent =
1997 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1998 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00001999 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2000 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002001 .build();
2002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2003 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2004 InputEventInjectionSync::WAIT_FOR_RESULT));
2005 rightWindow->consumeMotionMove();
2006
2007 leftWindow->assertNoEvents();
2008 rightWindow->assertNoEvents();
2009 wallpaperWindow->assertNoEvents();
2010}
2011
Arthur Hungc539dbb2022-12-08 07:45:36 +00002012/**
2013 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2014 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2015 * The right window should receive ACTION_DOWN.
2016 */
2017TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002019 sp<FakeWindowHandle> leftWindow =
2020 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2021 leftWindow->setFrame(Rect(0, 0, 200, 200));
2022 leftWindow->setDupTouchToWallpaper(true);
2023 leftWindow->setSlippery(true);
2024
2025 sp<FakeWindowHandle> rightWindow =
2026 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2027 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002028
2029 sp<FakeWindowHandle> wallpaperWindow =
2030 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2031 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002032
Arthur Hungc539dbb2022-12-08 07:45:36 +00002033 mDispatcher->setInputWindows(
2034 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002035
Arthur Hungc539dbb2022-12-08 07:45:36 +00002036 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002037 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2038 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002039 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002040 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002041
2042 // Both foreground window and its wallpaper should receive the touch down
2043 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002044 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2045
Arthur Hungc539dbb2022-12-08 07:45:36 +00002046 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002048 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2049 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002050 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2051
Arthur Hungc539dbb2022-12-08 07:45:36 +00002052 leftWindow->consumeMotionCancel();
2053 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2054 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002055}
2056
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002057/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002058 * Two windows: a window on the left and a window on the right.
2059 * Mouse is hovered from the right window into the left window.
2060 * Next, we tap on the left window, where the cursor was last seen.
2061 * The second tap is done onto the right window.
2062 * The mouse and tap are from two different devices.
2063 * We technically don't need to set the downtime / eventtime for these events, but setting these
2064 * explicitly helps during debugging.
2065 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2066 * In the buggy implementation, a tap on the right window would cause a crash.
2067 */
2068TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2069 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2070 sp<FakeWindowHandle> leftWindow =
2071 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2072 leftWindow->setFrame(Rect(0, 0, 200, 200));
2073
2074 sp<FakeWindowHandle> rightWindow =
2075 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2076 rightWindow->setFrame(Rect(200, 0, 400, 200));
2077
2078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2079 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2080 // stale.
2081 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2082 const int32_t mouseDeviceId = 6;
2083 const int32_t touchDeviceId = 4;
2084 // Move the cursor from right
2085 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2086 injectMotionEvent(mDispatcher,
2087 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2088 AINPUT_SOURCE_MOUSE)
2089 .deviceId(mouseDeviceId)
2090 .downTime(baseTime + 10)
2091 .eventTime(baseTime + 20)
2092 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2093 .x(300)
2094 .y(100))
2095 .build()));
2096 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2097
2098 // .. to the left window
2099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2100 injectMotionEvent(mDispatcher,
2101 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2102 AINPUT_SOURCE_MOUSE)
2103 .deviceId(mouseDeviceId)
2104 .downTime(baseTime + 10)
2105 .eventTime(baseTime + 30)
2106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2107 .x(110)
2108 .y(100))
2109 .build()));
2110 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2111 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2112 // Now tap the left window
2113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2114 injectMotionEvent(mDispatcher,
2115 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2116 AINPUT_SOURCE_TOUCHSCREEN)
2117 .deviceId(touchDeviceId)
2118 .downTime(baseTime + 40)
2119 .eventTime(baseTime + 40)
2120 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2121 .x(100)
2122 .y(100))
2123 .build()));
2124 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2125 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2126
2127 // release tap
2128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2129 injectMotionEvent(mDispatcher,
2130 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2131 AINPUT_SOURCE_TOUCHSCREEN)
2132 .deviceId(touchDeviceId)
2133 .downTime(baseTime + 40)
2134 .eventTime(baseTime + 50)
2135 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2136 .x(100)
2137 .y(100))
2138 .build()));
2139 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2140
2141 // Tap the window on the right
2142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2143 injectMotionEvent(mDispatcher,
2144 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2145 AINPUT_SOURCE_TOUCHSCREEN)
2146 .deviceId(touchDeviceId)
2147 .downTime(baseTime + 60)
2148 .eventTime(baseTime + 60)
2149 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2150 .x(300)
2151 .y(100))
2152 .build()));
2153 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2154
2155 // release tap
2156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2157 injectMotionEvent(mDispatcher,
2158 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2159 AINPUT_SOURCE_TOUCHSCREEN)
2160 .deviceId(touchDeviceId)
2161 .downTime(baseTime + 60)
2162 .eventTime(baseTime + 70)
2163 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2164 .x(300)
2165 .y(100))
2166 .build()));
2167 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2168
2169 // No more events
2170 leftWindow->assertNoEvents();
2171 rightWindow->assertNoEvents();
2172}
2173
2174/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002175 * On the display, have a single window, and also an area where there's no window.
2176 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2177 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2178 */
2179TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2181 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002182 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002183
2184 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2185 NotifyMotionArgs args;
2186
2187 // Touch down on the empty space
2188 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2189
2190 mDispatcher->waitForIdle();
2191 window->assertNoEvents();
2192
2193 // Now touch down on the window with another pointer
2194 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2195 mDispatcher->waitForIdle();
2196 window->consumeMotionDown();
2197}
2198
2199/**
2200 * Same test as above, but instead of touching the empty space, the first touch goes to
2201 * non-touchable window.
2202 */
2203TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2204 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2205 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002206 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002207 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2208 window1->setTouchable(false);
2209 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002210 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002211 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2212
2213 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2214
2215 NotifyMotionArgs args;
2216 // Touch down on the non-touchable window
2217 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2218
2219 mDispatcher->waitForIdle();
2220 window1->assertNoEvents();
2221 window2->assertNoEvents();
2222
2223 // Now touch down on the window with another pointer
2224 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2225 mDispatcher->waitForIdle();
2226 window2->consumeMotionDown();
2227}
2228
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002229/**
2230 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2231 * to the event time of the first ACTION_DOWN sent to the particular window.
2232 */
2233TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2234 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2235 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002236 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002237 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2238 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002239 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002240 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2241
2242 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2243
2244 NotifyMotionArgs args;
2245 // Touch down on the first window
2246 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2247
2248 mDispatcher->waitForIdle();
2249 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002250 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002251 window2->assertNoEvents();
2252 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2253 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2254 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2255
2256 // Now touch down on the window with another pointer
2257 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2258 mDispatcher->waitForIdle();
2259 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002260 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002261 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2262 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2263 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2264 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2265
2266 // Now move the pointer on the second window
2267 mDispatcher->notifyMotion(
2268 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2269 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002270 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002271
2272 // Now add new touch down on the second window
2273 mDispatcher->notifyMotion(
2274 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2275 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002276 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002277
2278 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2279 window1->consumeMotionMove();
2280 window1->assertNoEvents();
2281
2282 // Now move the pointer on the first window
2283 mDispatcher->notifyMotion(
2284 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2285 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002286 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002287
2288 mDispatcher->notifyMotion(&(
2289 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2290 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002291 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002292}
2293
Garfield Tandf26e862020-07-01 20:18:19 -07002294TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002295 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002296 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002297 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002298 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002299 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002300 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002301 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002302
2303 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2304
2305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2306
2307 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002309 injectMotionEvent(mDispatcher,
2310 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2311 AINPUT_SOURCE_MOUSE)
2312 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2313 .x(900)
2314 .y(400))
2315 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002316 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002317
2318 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002320 injectMotionEvent(mDispatcher,
2321 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2322 AINPUT_SOURCE_MOUSE)
2323 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2324 .x(300)
2325 .y(400))
2326 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002327 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2328 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002329
2330 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002332 injectMotionEvent(mDispatcher,
2333 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2334 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2335 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2336 .x(300)
2337 .y(400))
2338 .build()));
2339 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2340
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002342 injectMotionEvent(mDispatcher,
2343 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2344 AINPUT_SOURCE_MOUSE)
2345 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2346 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2347 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2348 .x(300)
2349 .y(400))
2350 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002351 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002352
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002354 injectMotionEvent(mDispatcher,
2355 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2356 AINPUT_SOURCE_MOUSE)
2357 .buttonState(0)
2358 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2359 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2360 .x(300)
2361 .y(400))
2362 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002363 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002366 injectMotionEvent(mDispatcher,
2367 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2368 .buttonState(0)
2369 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2370 .x(300)
2371 .y(400))
2372 .build()));
2373 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2374
2375 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002377 injectMotionEvent(mDispatcher,
2378 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2379 AINPUT_SOURCE_MOUSE)
2380 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2381 .x(900)
2382 .y(400))
2383 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002384 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2385 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002386
2387 // No more events
2388 windowLeft->assertNoEvents();
2389 windowRight->assertNoEvents();
2390}
2391
2392TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
2393 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2394
2395 sp<FakeWindowHandle> spyWindow =
2396 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2397 spyWindow->setFrame(Rect(0, 0, 600, 800));
2398 spyWindow->setTrustedOverlay(true);
2399 spyWindow->setSpy(true);
2400 sp<FakeWindowHandle> window =
2401 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2402 window->setFrame(Rect(0, 0, 600, 800));
2403
2404 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2406
2407 // Send mouse cursor to the window
2408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2409 injectMotionEvent(mDispatcher,
2410 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2411 AINPUT_SOURCE_MOUSE)
2412 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2413 .x(100)
2414 .y(100))
2415 .build()));
2416
2417 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2418 WithSource(AINPUT_SOURCE_MOUSE)));
2419 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2420 WithSource(AINPUT_SOURCE_MOUSE)));
2421
2422 window->assertNoEvents();
2423 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07002424}
2425
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002426TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
2427 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2428
2429 sp<FakeWindowHandle> spyWindow =
2430 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2431 spyWindow->setFrame(Rect(0, 0, 600, 800));
2432 spyWindow->setTrustedOverlay(true);
2433 spyWindow->setSpy(true);
2434 sp<FakeWindowHandle> window =
2435 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2436 window->setFrame(Rect(0, 0, 600, 800));
2437
2438 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2440
2441 // Send mouse cursor to the window
2442 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2443 injectMotionEvent(mDispatcher,
2444 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2445 AINPUT_SOURCE_MOUSE)
2446 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2447 .x(100)
2448 .y(100))
2449 .build()));
2450
2451 // Move mouse cursor
2452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2453 injectMotionEvent(mDispatcher,
2454 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2455 AINPUT_SOURCE_MOUSE)
2456 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2457 .x(110)
2458 .y(110))
2459 .build()));
2460
2461 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2462 WithSource(AINPUT_SOURCE_MOUSE)));
2463 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2464 WithSource(AINPUT_SOURCE_MOUSE)));
2465 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2466 WithSource(AINPUT_SOURCE_MOUSE)));
2467 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2468 WithSource(AINPUT_SOURCE_MOUSE)));
2469 // Touch down on the window
2470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2471 injectMotionEvent(mDispatcher,
2472 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2473 AINPUT_SOURCE_TOUCHSCREEN)
2474 .deviceId(SECOND_DEVICE_ID)
2475 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2476 .x(200)
2477 .y(200))
2478 .build()));
2479 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2480 WithSource(AINPUT_SOURCE_MOUSE)));
2481 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2482 WithSource(AINPUT_SOURCE_MOUSE)));
2483 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2484 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2485 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2486 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2487
2488 // pilfer the motion, retaining the gesture on the spy window.
2489 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2490 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
2491 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2492
2493 // Touch UP on the window
2494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2495 injectMotionEvent(mDispatcher,
2496 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2497 AINPUT_SOURCE_TOUCHSCREEN)
2498 .deviceId(SECOND_DEVICE_ID)
2499 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2500 .x(200)
2501 .y(200))
2502 .build()));
2503 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2504 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2505
2506 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
2507 // to send a new gesture. It should again go to both windows (spy and the window below), just
2508 // like the first gesture did, before pilfering. The window configuration has not changed.
2509
2510 // One more tap - DOWN
2511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2512 injectMotionEvent(mDispatcher,
2513 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2514 AINPUT_SOURCE_TOUCHSCREEN)
2515 .deviceId(SECOND_DEVICE_ID)
2516 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2517 .x(250)
2518 .y(250))
2519 .build()));
2520 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2521 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2522 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2523 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2524
2525 // Touch UP on the window
2526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2527 injectMotionEvent(mDispatcher,
2528 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2529 AINPUT_SOURCE_TOUCHSCREEN)
2530 .deviceId(SECOND_DEVICE_ID)
2531 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2532 .x(250)
2533 .y(250))
2534 .build()));
2535 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2536 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2537 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2538 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2539
2540 window->assertNoEvents();
2541 spyWindow->assertNoEvents();
2542}
2543
Garfield Tandf26e862020-07-01 20:18:19 -07002544// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2545// directly in this test.
2546TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002548 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002549 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002550 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002551
2552 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2553
2554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2555
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002557 injectMotionEvent(mDispatcher,
2558 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2559 AINPUT_SOURCE_MOUSE)
2560 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2561 .x(300)
2562 .y(400))
2563 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002564 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002565 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002567 injectMotionEvent(mDispatcher,
2568 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2569 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2570 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2571 .x(300)
2572 .y(400))
2573 .build()));
2574 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2575
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002577 injectMotionEvent(mDispatcher,
2578 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2579 AINPUT_SOURCE_MOUSE)
2580 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2581 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2582 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2583 .x(300)
2584 .y(400))
2585 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002586 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002587
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002589 injectMotionEvent(mDispatcher,
2590 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2591 AINPUT_SOURCE_MOUSE)
2592 .buttonState(0)
2593 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2594 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2595 .x(300)
2596 .y(400))
2597 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002598 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002599
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002601 injectMotionEvent(mDispatcher,
2602 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2603 .buttonState(0)
2604 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2605 .x(300)
2606 .y(400))
2607 .build()));
2608 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2609
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002611 injectMotionEvent(mDispatcher,
2612 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2613 AINPUT_SOURCE_MOUSE)
2614 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2615 .x(300)
2616 .y(400))
2617 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002618 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
Garfield Tandf26e862020-07-01 20:18:19 -07002619}
2620
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002621/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002622 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
2623 * is generated.
2624 */
2625TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
2626 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2627 sp<FakeWindowHandle> window =
2628 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2629 window->setFrame(Rect(0, 0, 1200, 800));
2630
2631 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2632
2633 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2634
2635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2636 injectMotionEvent(mDispatcher,
2637 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2638 AINPUT_SOURCE_MOUSE)
2639 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2640 .x(300)
2641 .y(400))
2642 .build()));
2643 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2644
2645 // Remove the window, but keep the channel.
2646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2647 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2648}
2649
2650/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002651 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002652 * The tap causes a HOVER_EXIT event to be generated because the current event
2653 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002654 */
2655TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2656 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2657 sp<FakeWindowHandle> window =
2658 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2659 window->setFrame(Rect(0, 0, 100, 100));
2660
2661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2662
2663 // Inject a hover_move from mouse.
2664 NotifyMotionArgs motionArgs =
2665 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2666 ADISPLAY_ID_DEFAULT, {{50, 50}});
2667 motionArgs.xCursorPosition = 50;
2668 motionArgs.yCursorPosition = 50;
2669 mDispatcher->notifyMotion(&motionArgs);
2670 ASSERT_NO_FATAL_FAILURE(
2671 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2672 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002673
2674 // Tap on the window
2675 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2676 ADISPLAY_ID_DEFAULT, {{10, 10}});
2677 mDispatcher->notifyMotion(&motionArgs);
2678 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002679 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2680 WithSource(AINPUT_SOURCE_MOUSE))));
2681
2682 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002683 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2684 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2685
2686 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2687 ADISPLAY_ID_DEFAULT, {{10, 10}});
2688 mDispatcher->notifyMotion(&motionArgs);
2689 ASSERT_NO_FATAL_FAILURE(
2690 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2691 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2692}
2693
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002694TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2695 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2696 sp<FakeWindowHandle> windowDefaultDisplay =
2697 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2698 ADISPLAY_ID_DEFAULT);
2699 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2700 sp<FakeWindowHandle> windowSecondDisplay =
2701 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2702 SECOND_DISPLAY_ID);
2703 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2704
2705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2706 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2707
2708 // Set cursor position in window in default display and check that hover enter and move
2709 // events are generated.
2710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2711 injectMotionEvent(mDispatcher,
2712 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2713 AINPUT_SOURCE_MOUSE)
2714 .displayId(ADISPLAY_ID_DEFAULT)
2715 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2716 .x(300)
2717 .y(600))
2718 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002719 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002720
2721 // Remove all windows in secondary display and check that no event happens on window in
2722 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002723 mDispatcher->setInputWindows(
2724 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002725 windowDefaultDisplay->assertNoEvents();
2726
2727 // Move cursor position in window in default display and check that only hover move
2728 // event is generated and not hover enter event.
2729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2730 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2732 injectMotionEvent(mDispatcher,
2733 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2734 AINPUT_SOURCE_MOUSE)
2735 .displayId(ADISPLAY_ID_DEFAULT)
2736 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2737 .x(400)
2738 .y(700))
2739 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002740 windowDefaultDisplay->consumeMotionEvent(
2741 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2742 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002743 windowDefaultDisplay->assertNoEvents();
2744}
2745
Garfield Tan00f511d2019-06-12 16:55:40 -07002746TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002748
2749 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002750 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002751 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002752 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002753 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002754 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002755
2756 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2757
Arthur Hung72d8dc32020-03-28 00:48:39 +00002758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002759
2760 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2761 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002763 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002764 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002765 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002766 windowRight->assertNoEvents();
2767}
2768
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002769TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002771 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2772 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002773 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002774
Arthur Hung72d8dc32020-03-28 00:48:39 +00002775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002776 setFocusedWindow(window);
2777
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002778 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002779
2780 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2781 mDispatcher->notifyKey(&keyArgs);
2782
2783 // Window should receive key down event.
2784 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2785
2786 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2787 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00002788 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002789 mDispatcher->notifyDeviceReset(&args);
2790 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2791 AKEY_EVENT_FLAG_CANCELED);
2792}
2793
2794TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002795 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002796 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2797 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002798
Arthur Hung72d8dc32020-03-28 00:48:39 +00002799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002800
2801 NotifyMotionArgs motionArgs =
2802 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2803 ADISPLAY_ID_DEFAULT);
2804 mDispatcher->notifyMotion(&motionArgs);
2805
2806 // Window should receive motion down event.
2807 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2808
2809 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2810 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00002811 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002812 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08002813 window->consumeMotionEvent(
2814 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002815}
2816
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002817TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2818 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002819 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2820 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002821 window->setFocusable(true);
2822
2823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2824 setFocusedWindow(window);
2825
2826 window->consumeFocusEvent(true);
2827
2828 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2829 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2830 const nsecs_t injectTime = keyArgs.eventTime;
2831 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2832 mDispatcher->notifyKey(&keyArgs);
2833 // The dispatching time should be always greater than or equal to intercept key timeout.
2834 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2835 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2836 std::chrono::nanoseconds(interceptKeyTimeout).count());
2837}
2838
2839TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2840 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002841 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2842 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002843 window->setFocusable(true);
2844
2845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2846 setFocusedWindow(window);
2847
2848 window->consumeFocusEvent(true);
2849
2850 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2851 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2852 mFakePolicy->setInterceptKeyTimeout(150ms);
2853 mDispatcher->notifyKey(&keyDown);
2854 mDispatcher->notifyKey(&keyUp);
2855
2856 // Window should receive key event immediately when same key up.
2857 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2858 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2859}
2860
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002861/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002862 * Two windows. First is a regular window. Second does not overlap with the first, and has
2863 * WATCH_OUTSIDE_TOUCH.
2864 * Both windows are owned by the same UID.
2865 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
2866 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
2867 */
2868TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
2869 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2870 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2871 "First Window", ADISPLAY_ID_DEFAULT);
2872 window->setFrame(Rect{0, 0, 100, 100});
2873
2874 sp<FakeWindowHandle> outsideWindow =
2875 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2876 ADISPLAY_ID_DEFAULT);
2877 outsideWindow->setFrame(Rect{100, 100, 200, 200});
2878 outsideWindow->setWatchOutsideTouch(true);
2879 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
2880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
2881
2882 // Tap on first window.
2883 NotifyMotionArgs motionArgs =
2884 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2885 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
2886 mDispatcher->notifyMotion(&motionArgs);
2887 window->consumeMotionDown();
2888 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
2889 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
2890 outsideWindow->consumeMotionEvent(
2891 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
2892}
2893
2894/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002895 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2896 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2897 * ACTION_OUTSIDE event is sent per gesture.
2898 */
2899TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2900 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2901 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002902 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2903 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002904 window->setWatchOutsideTouch(true);
2905 window->setFrame(Rect{0, 0, 100, 100});
2906 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002907 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2908 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002909 secondWindow->setFrame(Rect{100, 100, 200, 200});
2910 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002911 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2912 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002913 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2914 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2915
2916 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2917 NotifyMotionArgs motionArgs =
2918 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2919 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2920 mDispatcher->notifyMotion(&motionArgs);
2921 window->assertNoEvents();
2922 secondWindow->assertNoEvents();
2923
2924 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2925 // Now, `window` should get ACTION_OUTSIDE.
2926 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2927 {PointF{-10, -10}, PointF{105, 105}});
2928 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08002929 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
2930 window->consumeMotionEvent(
2931 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002932 secondWindow->consumeMotionDown();
2933 thirdWindow->assertNoEvents();
2934
2935 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2936 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2937 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2938 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2939 mDispatcher->notifyMotion(&motionArgs);
2940 window->assertNoEvents();
2941 secondWindow->consumeMotionMove();
2942 thirdWindow->consumeMotionDown();
2943}
2944
Prabir Pradhan814fe082022-07-22 20:22:18 +00002945TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002947 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2948 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002949 window->setFocusable(true);
2950
2951 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2952 setFocusedWindow(window);
2953
2954 window->consumeFocusEvent(true);
2955
2956 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2957 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2958 mDispatcher->notifyKey(&keyDown);
2959 mDispatcher->notifyKey(&keyUp);
2960
2961 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2962 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2963
2964 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2965 mDispatcher->onWindowInfosChanged({}, {});
2966
2967 window->consumeFocusEvent(false);
2968
2969 mDispatcher->notifyKey(&keyDown);
2970 mDispatcher->notifyKey(&keyUp);
2971 window->assertNoEvents();
2972}
2973
Arthur Hung96483742022-11-15 03:30:48 +00002974TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2975 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2976 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2977 "Fake Window", ADISPLAY_ID_DEFAULT);
2978 // Ensure window is non-split and have some transform.
2979 window->setPreventSplitting(true);
2980 window->setWindowOffset(20, 40);
2981 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2982
2983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2984 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2985 {50, 50}))
2986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2987 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2988
2989 const MotionEvent secondFingerDownEvent =
2990 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2991 .displayId(ADISPLAY_ID_DEFAULT)
2992 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002993 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2994 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00002995 .build();
2996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2997 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2998 InputEventInjectionSync::WAIT_FOR_RESULT))
2999 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3000
3001 const MotionEvent* event = window->consumeMotion();
3002 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3003 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3004 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3005 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3006 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3007}
3008
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003009/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003010 * Ensure the correct coordinate spaces are used by InputDispatcher.
3011 *
3012 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3013 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3014 * space.
3015 */
3016class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3017public:
3018 void SetUp() override {
3019 InputDispatcherTest::SetUp();
3020 mDisplayInfos.clear();
3021 mWindowInfos.clear();
3022 }
3023
3024 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3025 gui::DisplayInfo info;
3026 info.displayId = displayId;
3027 info.transform = transform;
3028 mDisplayInfos.push_back(std::move(info));
3029 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3030 }
3031
3032 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3033 mWindowInfos.push_back(*windowHandle->getInfo());
3034 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3035 }
3036
3037 // Set up a test scenario where the display has a scaled projection and there are two windows
3038 // on the display.
3039 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3040 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3041 // respectively.
3042 ui::Transform displayTransform;
3043 displayTransform.set(2, 0, 0, 4);
3044 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3045
3046 std::shared_ptr<FakeApplicationHandle> application =
3047 std::make_shared<FakeApplicationHandle>();
3048
3049 // Add two windows to the display. Their frames are represented in the display space.
3050 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003051 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3052 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003053 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3054 addWindow(firstWindow);
3055
3056 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003057 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3058 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003059 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3060 addWindow(secondWindow);
3061 return {std::move(firstWindow), std::move(secondWindow)};
3062 }
3063
3064private:
3065 std::vector<gui::DisplayInfo> mDisplayInfos;
3066 std::vector<gui::WindowInfo> mWindowInfos;
3067};
3068
3069TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3070 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3071 // Send down to the first window. The point is represented in the display space. The point is
3072 // selected so that if the hit test was done with the transform applied to it, then it would
3073 // end up in the incorrect window.
3074 NotifyMotionArgs downMotionArgs =
3075 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3076 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3077 mDispatcher->notifyMotion(&downMotionArgs);
3078
3079 firstWindow->consumeMotionDown();
3080 secondWindow->assertNoEvents();
3081}
3082
3083// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3084// the event should be treated as being in the logical display space.
3085TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3086 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3087 // Send down to the first window. The point is represented in the logical display space. The
3088 // point is selected so that if the hit test was done in logical display space, then it would
3089 // end up in the incorrect window.
3090 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3091 PointF{75 * 2, 55 * 4});
3092
3093 firstWindow->consumeMotionDown();
3094 secondWindow->assertNoEvents();
3095}
3096
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003097// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3098// event should be treated as being in the logical display space.
3099TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3100 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3101
3102 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3103 ui::Transform injectedEventTransform;
3104 injectedEventTransform.set(matrix);
3105 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
3106 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
3107
3108 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3109 .displayId(ADISPLAY_ID_DEFAULT)
3110 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003111 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003112 .x(untransformedPoint.x)
3113 .y(untransformedPoint.y))
3114 .build();
3115 event.transform(matrix);
3116
3117 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
3118 InputEventInjectionSync::WAIT_FOR_RESULT);
3119
3120 firstWindow->consumeMotionDown();
3121 secondWindow->assertNoEvents();
3122}
3123
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003124TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
3125 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3126
3127 // Send down to the second window.
3128 NotifyMotionArgs downMotionArgs =
3129 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3130 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
3131 mDispatcher->notifyMotion(&downMotionArgs);
3132
3133 firstWindow->assertNoEvents();
3134 const MotionEvent* event = secondWindow->consumeMotion();
3135 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
3136
3137 // Ensure that the events from the "getRaw" API are in logical display coordinates.
3138 EXPECT_EQ(300, event->getRawX(0));
3139 EXPECT_EQ(880, event->getRawY(0));
3140
3141 // Ensure that the x and y values are in the window's coordinate space.
3142 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
3143 // the logical display space. This will be the origin of the window space.
3144 EXPECT_EQ(100, event->getX(0));
3145 EXPECT_EQ(80, event->getY(0));
3146}
3147
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003148using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
3149 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003150
3151class TransferTouchFixture : public InputDispatcherTest,
3152 public ::testing::WithParamInterface<TransferFunction> {};
3153
3154TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07003155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003156
3157 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003158 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003159 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3160 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003161 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003162 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003163 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3164 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003165 sp<FakeWindowHandle> wallpaper =
3166 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
3167 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003168 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00003169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003170
3171 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003172 NotifyMotionArgs downMotionArgs =
3173 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3174 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003175 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003176
Svet Ganov5d3bc372020-01-26 23:11:07 -08003177 // Only the first window should get the down event
3178 firstWindow->consumeMotionDown();
3179 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003180 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003181
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003182 // Transfer touch to the second window
3183 TransferFunction f = GetParam();
3184 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3185 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003186 // The first window gets cancel and the second gets down
3187 firstWindow->consumeMotionCancel();
3188 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003189 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003190
3191 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003192 NotifyMotionArgs upMotionArgs =
3193 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3194 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003195 mDispatcher->notifyMotion(&upMotionArgs);
3196 // The first window gets no events and the second gets up
3197 firstWindow->assertNoEvents();
3198 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003199 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003200}
3201
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003202/**
3203 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
3204 * from. When we have spy windows, there are several windows to choose from: either spy, or the
3205 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
3206 * natural to the user.
3207 * In this test, we are sending a pointer to both spy window and first window. We then try to
3208 * transfer touch to the second window. The dispatcher should identify the first window as the
3209 * one that should lose the gesture, and therefore the action should be to move the gesture from
3210 * the first window to the second.
3211 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
3212 * the other API, as well.
3213 */
3214TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
3215 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3216
3217 // Create a couple of windows + a spy window
3218 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003219 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003220 spyWindow->setTrustedOverlay(true);
3221 spyWindow->setSpy(true);
3222 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003223 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003224 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003225 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003226
3227 // Add the windows to the dispatcher
3228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
3229
3230 // Send down to the first window
3231 NotifyMotionArgs downMotionArgs =
3232 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3233 ADISPLAY_ID_DEFAULT);
3234 mDispatcher->notifyMotion(&downMotionArgs);
3235 // Only the first window and spy should get the down event
3236 spyWindow->consumeMotionDown();
3237 firstWindow->consumeMotionDown();
3238
3239 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
3240 // if f === 'transferTouch'.
3241 TransferFunction f = GetParam();
3242 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3243 ASSERT_TRUE(success);
3244 // The first window gets cancel and the second gets down
3245 firstWindow->consumeMotionCancel();
3246 secondWindow->consumeMotionDown();
3247
3248 // Send up event to the second window
3249 NotifyMotionArgs upMotionArgs =
3250 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3251 ADISPLAY_ID_DEFAULT);
3252 mDispatcher->notifyMotion(&upMotionArgs);
3253 // The first window gets no events and the second+spy get up
3254 firstWindow->assertNoEvents();
3255 spyWindow->consumeMotionUp();
3256 secondWindow->consumeMotionUp();
3257}
3258
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003259TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003261
3262 PointF touchPoint = {10, 10};
3263
3264 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003265 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003266 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3267 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003268 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003269 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003270 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3271 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003272 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003273
3274 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003276
3277 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003278 NotifyMotionArgs downMotionArgs =
3279 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3280 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003281 mDispatcher->notifyMotion(&downMotionArgs);
3282 // Only the first window should get the down event
3283 firstWindow->consumeMotionDown();
3284 secondWindow->assertNoEvents();
3285
3286 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003287 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003288 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003289 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003290 mDispatcher->notifyMotion(&pointerDownMotionArgs);
3291 // Only the first window should get the pointer down event
3292 firstWindow->consumeMotionPointerDown(1);
3293 secondWindow->assertNoEvents();
3294
3295 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003296 TransferFunction f = GetParam();
3297 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3298 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003299 // The first window gets cancel and the second gets down and pointer down
3300 firstWindow->consumeMotionCancel();
3301 secondWindow->consumeMotionDown();
3302 secondWindow->consumeMotionPointerDown(1);
3303
3304 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003305 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003306 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003307 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003308 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3309 // The first window gets nothing and the second gets pointer up
3310 firstWindow->assertNoEvents();
3311 secondWindow->consumeMotionPointerUp(1);
3312
3313 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003314 NotifyMotionArgs upMotionArgs =
3315 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3316 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003317 mDispatcher->notifyMotion(&upMotionArgs);
3318 // The first window gets nothing and the second gets up
3319 firstWindow->assertNoEvents();
3320 secondWindow->consumeMotionUp();
3321}
3322
Arthur Hungc539dbb2022-12-08 07:45:36 +00003323TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
3324 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3325
3326 // Create a couple of windows
3327 sp<FakeWindowHandle> firstWindow =
3328 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3329 ADISPLAY_ID_DEFAULT);
3330 firstWindow->setDupTouchToWallpaper(true);
3331 sp<FakeWindowHandle> secondWindow =
3332 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3333 ADISPLAY_ID_DEFAULT);
3334 secondWindow->setDupTouchToWallpaper(true);
3335
3336 sp<FakeWindowHandle> wallpaper1 =
3337 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
3338 wallpaper1->setIsWallpaper(true);
3339
3340 sp<FakeWindowHandle> wallpaper2 =
3341 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
3342 wallpaper2->setIsWallpaper(true);
3343 // Add the windows to the dispatcher
3344 mDispatcher->setInputWindows(
3345 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
3346
3347 // Send down to the first window
3348 NotifyMotionArgs downMotionArgs =
3349 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3350 ADISPLAY_ID_DEFAULT);
3351 mDispatcher->notifyMotion(&downMotionArgs);
3352
3353 // Only the first window should get the down event
3354 firstWindow->consumeMotionDown();
3355 secondWindow->assertNoEvents();
3356 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3357 wallpaper2->assertNoEvents();
3358
3359 // Transfer touch focus to the second window
3360 TransferFunction f = GetParam();
3361 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3362 ASSERT_TRUE(success);
3363
3364 // The first window gets cancel and the second gets down
3365 firstWindow->consumeMotionCancel();
3366 secondWindow->consumeMotionDown();
3367 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3368 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3369
3370 // Send up event to the second window
3371 NotifyMotionArgs upMotionArgs =
3372 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3373 ADISPLAY_ID_DEFAULT);
3374 mDispatcher->notifyMotion(&upMotionArgs);
3375 // The first window gets no events and the second gets up
3376 firstWindow->assertNoEvents();
3377 secondWindow->consumeMotionUp();
3378 wallpaper1->assertNoEvents();
3379 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3380}
3381
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003382// For the cases of single pointer touch and two pointers non-split touch, the api's
3383// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
3384// for the case where there are multiple pointers split across several windows.
3385INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
3386 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003387 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3388 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003389 return dispatcher->transferTouch(destChannelToken,
3390 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003391 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003392 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3393 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003394 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00003395 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003396 }));
3397
Svet Ganov5d3bc372020-01-26 23:11:07 -08003398TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003399 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003400
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003401 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003402 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3403 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003404 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003405
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003406 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003407 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3408 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003409 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003410
3411 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003413
3414 PointF pointInFirst = {300, 200};
3415 PointF pointInSecond = {300, 600};
3416
3417 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003418 NotifyMotionArgs firstDownMotionArgs =
3419 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3420 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003421 mDispatcher->notifyMotion(&firstDownMotionArgs);
3422 // Only the first window should get the down event
3423 firstWindow->consumeMotionDown();
3424 secondWindow->assertNoEvents();
3425
3426 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003427 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003428 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003429 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003430 mDispatcher->notifyMotion(&secondDownMotionArgs);
3431 // The first window gets a move and the second a down
3432 firstWindow->consumeMotionMove();
3433 secondWindow->consumeMotionDown();
3434
3435 // Transfer touch focus to the second window
3436 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
3437 // The first window gets cancel and the new gets pointer down (it already saw down)
3438 firstWindow->consumeMotionCancel();
3439 secondWindow->consumeMotionPointerDown(1);
3440
3441 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003442 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003443 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003444 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003445 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3446 // The first window gets nothing and the second gets pointer up
3447 firstWindow->assertNoEvents();
3448 secondWindow->consumeMotionPointerUp(1);
3449
3450 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003451 NotifyMotionArgs upMotionArgs =
3452 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3453 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003454 mDispatcher->notifyMotion(&upMotionArgs);
3455 // The first window gets nothing and the second gets up
3456 firstWindow->assertNoEvents();
3457 secondWindow->consumeMotionUp();
3458}
3459
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003460// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3461// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3462// touch is not supported, so the touch should continue on those windows and the transferred-to
3463// window should get nothing.
3464TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3465 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3466
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003467 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003468 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3469 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003470 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003471
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003472 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003473 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3474 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003475 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003476
3477 // Add the windows to the dispatcher
3478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3479
3480 PointF pointInFirst = {300, 200};
3481 PointF pointInSecond = {300, 600};
3482
3483 // Send down to the first window
3484 NotifyMotionArgs firstDownMotionArgs =
3485 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3486 ADISPLAY_ID_DEFAULT, {pointInFirst});
3487 mDispatcher->notifyMotion(&firstDownMotionArgs);
3488 // Only the first window should get the down event
3489 firstWindow->consumeMotionDown();
3490 secondWindow->assertNoEvents();
3491
3492 // Send down to the second window
3493 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003494 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003495 {pointInFirst, pointInSecond});
3496 mDispatcher->notifyMotion(&secondDownMotionArgs);
3497 // The first window gets a move and the second a down
3498 firstWindow->consumeMotionMove();
3499 secondWindow->consumeMotionDown();
3500
3501 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003502 const bool transferred =
3503 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003504 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3505 ASSERT_FALSE(transferred);
3506 firstWindow->assertNoEvents();
3507 secondWindow->assertNoEvents();
3508
3509 // The rest of the dispatch should proceed as normal
3510 // Send pointer up to the second window
3511 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003512 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003513 {pointInFirst, pointInSecond});
3514 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3515 // The first window gets MOVE and the second gets pointer up
3516 firstWindow->consumeMotionMove();
3517 secondWindow->consumeMotionUp();
3518
3519 // Send up event to the first window
3520 NotifyMotionArgs upMotionArgs =
3521 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3522 ADISPLAY_ID_DEFAULT);
3523 mDispatcher->notifyMotion(&upMotionArgs);
3524 // The first window gets nothing and the second gets up
3525 firstWindow->consumeMotionUp();
3526 secondWindow->assertNoEvents();
3527}
3528
Arthur Hungabbb9d82021-09-01 14:52:30 +00003529// This case will create two windows and one mirrored window on the default display and mirror
3530// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3531// the windows info of second display before default display.
3532TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3533 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3534 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003535 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003536 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003537 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003538 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003539 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003540
3541 sp<FakeWindowHandle> mirrorWindowInPrimary =
3542 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3543 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003544
3545 sp<FakeWindowHandle> firstWindowInSecondary =
3546 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3547 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003548
3549 sp<FakeWindowHandle> secondWindowInSecondary =
3550 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3551 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003552
3553 // Update window info, let it find window handle of second display first.
3554 mDispatcher->setInputWindows(
3555 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3556 {ADISPLAY_ID_DEFAULT,
3557 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3558
3559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3560 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3561 {50, 50}))
3562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3563
3564 // Window should receive motion event.
3565 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3566
3567 // Transfer touch focus
3568 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3569 secondWindowInPrimary->getToken()));
3570 // The first window gets cancel.
3571 firstWindowInPrimary->consumeMotionCancel();
3572 secondWindowInPrimary->consumeMotionDown();
3573
3574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3575 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3576 ADISPLAY_ID_DEFAULT, {150, 50}))
3577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3578 firstWindowInPrimary->assertNoEvents();
3579 secondWindowInPrimary->consumeMotionMove();
3580
3581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3582 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3583 {150, 50}))
3584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3585 firstWindowInPrimary->assertNoEvents();
3586 secondWindowInPrimary->consumeMotionUp();
3587}
3588
3589// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3590// 'transferTouch' api.
3591TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3592 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3593 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003594 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003595 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003596 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003597 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003598 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003599
3600 sp<FakeWindowHandle> mirrorWindowInPrimary =
3601 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3602 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003603
3604 sp<FakeWindowHandle> firstWindowInSecondary =
3605 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3606 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003607
3608 sp<FakeWindowHandle> secondWindowInSecondary =
3609 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3610 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003611
3612 // Update window info, let it find window handle of second display first.
3613 mDispatcher->setInputWindows(
3614 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3615 {ADISPLAY_ID_DEFAULT,
3616 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3617
3618 // Touch on second display.
3619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3620 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3622
3623 // Window should receive motion event.
3624 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3625
3626 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003627 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003628
3629 // The first window gets cancel.
3630 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3631 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3632
3633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3634 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3635 SECOND_DISPLAY_ID, {150, 50}))
3636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3637 firstWindowInPrimary->assertNoEvents();
3638 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3639
3640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3641 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3642 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3643 firstWindowInPrimary->assertNoEvents();
3644 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3645}
3646
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003647TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003649 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3650 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003651
Vishnu Nair47074b82020-08-14 11:54:47 -07003652 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003654 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003655
3656 window->consumeFocusEvent(true);
3657
3658 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3659 mDispatcher->notifyKey(&keyArgs);
3660
3661 // Window should receive key down event.
3662 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3663}
3664
3665TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003667 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3668 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003669
Arthur Hung72d8dc32020-03-28 00:48:39 +00003670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003671
3672 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3673 mDispatcher->notifyKey(&keyArgs);
3674 mDispatcher->waitForIdle();
3675
3676 window->assertNoEvents();
3677}
3678
3679// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3680TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003681 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003682 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3683 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003684
Arthur Hung72d8dc32020-03-28 00:48:39 +00003685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003686
3687 // Send key
3688 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3689 mDispatcher->notifyKey(&keyArgs);
3690 // Send motion
3691 NotifyMotionArgs motionArgs =
3692 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3693 ADISPLAY_ID_DEFAULT);
3694 mDispatcher->notifyMotion(&motionArgs);
3695
3696 // Window should receive only the motion event
3697 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3698 window->assertNoEvents(); // Key event or focus event will not be received
3699}
3700
arthurhungea3f4fc2020-12-21 23:18:53 +08003701TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3702 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3703
arthurhungea3f4fc2020-12-21 23:18:53 +08003704 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003705 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3706 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003707 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003708
arthurhungea3f4fc2020-12-21 23:18:53 +08003709 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003710 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3711 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003712 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003713
3714 // Add the windows to the dispatcher
3715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3716
3717 PointF pointInFirst = {300, 200};
3718 PointF pointInSecond = {300, 600};
3719
3720 // Send down to the first window
3721 NotifyMotionArgs firstDownMotionArgs =
3722 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3723 ADISPLAY_ID_DEFAULT, {pointInFirst});
3724 mDispatcher->notifyMotion(&firstDownMotionArgs);
3725 // Only the first window should get the down event
3726 firstWindow->consumeMotionDown();
3727 secondWindow->assertNoEvents();
3728
3729 // Send down to the second window
3730 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003731 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003732 {pointInFirst, pointInSecond});
3733 mDispatcher->notifyMotion(&secondDownMotionArgs);
3734 // The first window gets a move and the second a down
3735 firstWindow->consumeMotionMove();
3736 secondWindow->consumeMotionDown();
3737
3738 // Send pointer cancel to the second window
3739 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003740 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003741 {pointInFirst, pointInSecond});
3742 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3743 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3744 // The first window gets move and the second gets cancel.
3745 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3746 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3747
3748 // Send up event.
3749 NotifyMotionArgs upMotionArgs =
3750 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3751 ADISPLAY_ID_DEFAULT);
3752 mDispatcher->notifyMotion(&upMotionArgs);
3753 // The first window gets up and the second gets nothing.
3754 firstWindow->consumeMotionUp();
3755 secondWindow->assertNoEvents();
3756}
3757
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003758TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3759 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3760
3761 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003762 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3764 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3765 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3766 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3767
Harry Cutts33476232023-01-30 19:57:29 +00003768 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003769 window->assertNoEvents();
3770 mDispatcher->waitForIdle();
3771}
3772
chaviwd1c23182019-12-20 18:44:56 -08003773class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003774public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003775 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003776 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003777 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003778 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003779 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003780 }
3781
chaviwd1c23182019-12-20 18:44:56 -08003782 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3783
3784 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3785 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3786 expectedDisplayId, expectedFlags);
3787 }
3788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003789 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3790
3791 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3792
chaviwd1c23182019-12-20 18:44:56 -08003793 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3794 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3795 expectedDisplayId, expectedFlags);
3796 }
3797
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003798 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3799 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3800 expectedDisplayId, expectedFlags);
3801 }
3802
chaviwd1c23182019-12-20 18:44:56 -08003803 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3804 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3805 expectedDisplayId, expectedFlags);
3806 }
3807
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003808 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003809 mInputReceiver->consumeMotionEvent(
3810 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
3811 WithDisplayId(expectedDisplayId),
3812 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003813 }
3814
Arthur Hungfbfa5722021-11-16 02:45:54 +00003815 void consumeMotionPointerDown(int32_t pointerIdx) {
3816 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3817 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3818 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00003819 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00003820 }
3821
Evan Rosky84f07f02021-04-16 10:42:42 -07003822 MotionEvent* consumeMotion() {
3823 InputEvent* event = mInputReceiver->consume();
3824 if (!event) {
3825 ADD_FAILURE() << "No event was produced";
3826 return nullptr;
3827 }
3828 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3829 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3830 return nullptr;
3831 }
3832 return static_cast<MotionEvent*>(event);
3833 }
3834
chaviwd1c23182019-12-20 18:44:56 -08003835 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3836
3837private:
3838 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003839};
3840
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003841using InputDispatcherMonitorTest = InputDispatcherTest;
3842
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003843/**
3844 * Two entities that receive touch: A window, and a global monitor.
3845 * The touch goes to the window, and then the window disappears.
3846 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3847 * for the monitor, as well.
3848 * 1. foregroundWindow
3849 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3850 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003851TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003852 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3853 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003854 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003855
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003856 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003857
3858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3860 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3861 {100, 200}))
3862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3863
3864 // Both the foreground window and the global monitor should receive the touch down
3865 window->consumeMotionDown();
3866 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3867
3868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3870 ADISPLAY_ID_DEFAULT, {110, 200}))
3871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3872
3873 window->consumeMotionMove();
3874 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3875
3876 // Now the foreground window goes away
3877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3878 window->consumeMotionCancel();
3879 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3880
3881 // If more events come in, there will be no more foreground window to send them to. This will
3882 // cause a cancel for the monitor, as well.
3883 ASSERT_EQ(InputEventInjectionResult::FAILED,
3884 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3885 ADISPLAY_ID_DEFAULT, {120, 200}))
3886 << "Injection should fail because the window was removed";
3887 window->assertNoEvents();
3888 // Global monitor now gets the cancel
3889 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3890}
3891
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003892TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003893 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003894 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3895 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003897
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003898 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003899
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003903 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003904 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003905}
3906
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003907TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3908 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003909
Chris Yea209fde2020-07-22 13:54:51 -07003910 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003911 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3912 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003918 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003919 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003920
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003921 // Pilfer pointers from the monitor.
3922 // This should not do anything and the window should continue to receive events.
3923 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003926 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3927 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003929
3930 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3931 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003932}
3933
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003934TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003936 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3937 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3939 window->setWindowOffset(20, 40);
3940 window->setWindowTransform(0, 1, -1, 0);
3941
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003942 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003943
3944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3947 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3948 MotionEvent* event = monitor.consumeMotion();
3949 // Even though window has transform, gesture monitor must not.
3950 ASSERT_EQ(ui::Transform(), event->getTransform());
3951}
3952
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003953TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003954 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003955 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003956
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003957 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003958 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003959 << "Injection should fail if there is a monitor, but no touchable window";
3960 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003961}
3962
chaviw81e2bb92019-12-18 15:03:51 -08003963TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003964 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003965 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3966 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003967
Arthur Hung72d8dc32020-03-28 00:48:39 +00003968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003969
3970 NotifyMotionArgs motionArgs =
3971 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3972 ADISPLAY_ID_DEFAULT);
3973
3974 mDispatcher->notifyMotion(&motionArgs);
3975 // Window should receive motion down event.
3976 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3977
3978 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003979 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003980 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3981 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3982 motionArgs.pointerCoords[0].getX() - 10);
3983
3984 mDispatcher->notifyMotion(&motionArgs);
3985 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00003986 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08003987}
3988
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003989/**
3990 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3991 * the device default right away. In the test scenario, we check both the default value,
3992 * and the action of enabling / disabling.
3993 */
3994TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003996 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3997 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003998 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003999
4000 // Set focused application.
4001 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004002 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004003
4004 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004006 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004007 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004008
4009 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004010 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004012 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004013
4014 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004015 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004016 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004017 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004018 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004020 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004021 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004022
4023 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004024 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004026 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004027
4028 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004029 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004030 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004031 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004032 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004034 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004035 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004036
4037 window->assertNoEvents();
4038}
4039
Gang Wange9087892020-01-07 12:17:14 -05004040TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004041 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004042 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4043 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004044
4045 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004046 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004047
Arthur Hung72d8dc32020-03-28 00:48:39 +00004048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004049 setFocusedWindow(window);
4050
Harry Cutts33476232023-01-30 19:57:29 +00004051 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004052
4053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4054 mDispatcher->notifyKey(&keyArgs);
4055
4056 InputEvent* event = window->consume();
4057 ASSERT_NE(event, nullptr);
4058
4059 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4060 ASSERT_NE(verified, nullptr);
4061 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4062
4063 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4064 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4065 ASSERT_EQ(keyArgs.source, verified->source);
4066 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4067
4068 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4069
4070 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004071 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004072 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004073 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4074 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4075 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4076 ASSERT_EQ(0, verifiedKey.repeatCount);
4077}
4078
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004079TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004080 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004081 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4082 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004083
4084 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4085
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004086 ui::Transform transform;
4087 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4088
4089 gui::DisplayInfo displayInfo;
4090 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
4091 displayInfo.transform = transform;
4092
4093 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004094
4095 NotifyMotionArgs motionArgs =
4096 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4097 ADISPLAY_ID_DEFAULT);
4098 mDispatcher->notifyMotion(&motionArgs);
4099
4100 InputEvent* event = window->consume();
4101 ASSERT_NE(event, nullptr);
4102
4103 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4104 ASSERT_NE(verified, nullptr);
4105 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
4106
4107 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
4108 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
4109 EXPECT_EQ(motionArgs.source, verified->source);
4110 EXPECT_EQ(motionArgs.displayId, verified->displayId);
4111
4112 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
4113
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004114 const vec2 rawXY =
4115 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
4116 motionArgs.pointerCoords[0].getXYValue());
4117 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
4118 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004119 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004120 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004121 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004122 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
4123 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
4124}
4125
chaviw09c8d2d2020-08-24 15:48:26 -07004126/**
4127 * Ensure that separate calls to sign the same data are generating the same key.
4128 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
4129 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
4130 * tests.
4131 */
4132TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
4133 KeyEvent event = getTestKeyEvent();
4134 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4135
4136 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
4137 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
4138 ASSERT_EQ(hmac1, hmac2);
4139}
4140
4141/**
4142 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
4143 */
4144TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
4145 KeyEvent event = getTestKeyEvent();
4146 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4147 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
4148
4149 verifiedEvent.deviceId += 1;
4150 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4151
4152 verifiedEvent.source += 1;
4153 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4154
4155 verifiedEvent.eventTimeNanos += 1;
4156 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4157
4158 verifiedEvent.displayId += 1;
4159 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4160
4161 verifiedEvent.action += 1;
4162 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4163
4164 verifiedEvent.downTimeNanos += 1;
4165 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4166
4167 verifiedEvent.flags += 1;
4168 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4169
4170 verifiedEvent.keyCode += 1;
4171 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4172
4173 verifiedEvent.scanCode += 1;
4174 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4175
4176 verifiedEvent.metaState += 1;
4177 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4178
4179 verifiedEvent.repeatCount += 1;
4180 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4181}
4182
Vishnu Nair958da932020-08-21 17:12:37 -07004183TEST_F(InputDispatcherTest, SetFocusedWindow) {
4184 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4185 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004186 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004187 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004188 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004189 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4190
4191 // Top window is also focusable but is not granted focus.
4192 windowTop->setFocusable(true);
4193 windowSecond->setFocusable(true);
4194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4195 setFocusedWindow(windowSecond);
4196
4197 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4199 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004200
4201 // Focused window should receive event.
4202 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4203 windowTop->assertNoEvents();
4204}
4205
4206TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
4207 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4208 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004209 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004210 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4211
4212 window->setFocusable(true);
4213 // Release channel for window is no longer valid.
4214 window->releaseChannel();
4215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4216 setFocusedWindow(window);
4217
4218 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4220 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004221
4222 // window channel is invalid, so it should not receive any input event.
4223 window->assertNoEvents();
4224}
4225
4226TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
4227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4228 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004229 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004230 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07004231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4232
Vishnu Nair958da932020-08-21 17:12:37 -07004233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4234 setFocusedWindow(window);
4235
4236 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004237 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4238 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004239
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004240 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07004241 window->assertNoEvents();
4242}
4243
4244TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
4245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4246 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004247 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004248 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004249 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004250 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4251
4252 windowTop->setFocusable(true);
4253 windowSecond->setFocusable(true);
4254 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4255 setFocusedWindow(windowTop);
4256 windowTop->consumeFocusEvent(true);
4257
4258 setFocusedWindow(windowSecond, windowTop);
4259 windowSecond->consumeFocusEvent(true);
4260 windowTop->consumeFocusEvent(false);
4261
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4263 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004264
4265 // Focused window should receive event.
4266 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4267}
4268
4269TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
4270 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4271 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004272 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004273 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004274 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004275 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4276
4277 windowTop->setFocusable(true);
4278 windowSecond->setFocusable(true);
4279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4280 setFocusedWindow(windowSecond, windowTop);
4281
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004282 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4283 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004284
4285 // Event should be dropped.
4286 windowTop->assertNoEvents();
4287 windowSecond->assertNoEvents();
4288}
4289
4290TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
4291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4292 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004293 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004294 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004295 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
4296 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004297 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4298
4299 window->setFocusable(true);
4300 previousFocusedWindow->setFocusable(true);
4301 window->setVisible(false);
4302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
4303 setFocusedWindow(previousFocusedWindow);
4304 previousFocusedWindow->consumeFocusEvent(true);
4305
4306 // Requesting focus on invisible window takes focus from currently focused window.
4307 setFocusedWindow(window);
4308 previousFocusedWindow->consumeFocusEvent(false);
4309
4310 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00004312 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
4313 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004314
4315 // Window does not get focus event or key down.
4316 window->assertNoEvents();
4317
4318 // Window becomes visible.
4319 window->setVisible(true);
4320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4321
4322 // Window receives focus event.
4323 window->consumeFocusEvent(true);
4324 // Focused window receives key down.
4325 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4326}
4327
Vishnu Nair599f1412021-06-21 10:39:58 -07004328TEST_F(InputDispatcherTest, DisplayRemoved) {
4329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4330 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004331 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07004332 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4333
4334 // window is granted focus.
4335 window->setFocusable(true);
4336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4337 setFocusedWindow(window);
4338 window->consumeFocusEvent(true);
4339
4340 // When a display is removed window loses focus.
4341 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
4342 window->consumeFocusEvent(false);
4343}
4344
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004345/**
4346 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
4347 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
4348 * of the 'slipperyEnterWindow'.
4349 *
4350 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
4351 * a way so that the touched location is no longer covered by the top window.
4352 *
4353 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
4354 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
4355 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
4356 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
4357 * with ACTION_DOWN).
4358 * Thus, the touch has been transferred from the top window into the bottom window, because the top
4359 * window moved itself away from the touched location and had Flag::SLIPPERY.
4360 *
4361 * Even though the top window moved away from the touched location, it is still obscuring the bottom
4362 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
4363 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
4364 *
4365 * In this test, we ensure that the event received by the bottom window has
4366 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
4367 */
4368TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004369 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
4370 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004371
4372 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4373 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4374
4375 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004376 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004377 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004378 // Make sure this one overlaps the bottom window
4379 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
4380 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
4381 // one. Windows with the same owner are not considered to be occluding each other.
4382 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
4383
4384 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004385 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004386 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
4387
4388 mDispatcher->setInputWindows(
4389 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4390
4391 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
4392 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4393 ADISPLAY_ID_DEFAULT, {{50, 50}});
4394 mDispatcher->notifyMotion(&args);
4395 slipperyExitWindow->consumeMotionDown();
4396 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
4397 mDispatcher->setInputWindows(
4398 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4399
4400 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4401 ADISPLAY_ID_DEFAULT, {{51, 51}});
4402 mDispatcher->notifyMotion(&args);
4403
4404 slipperyExitWindow->consumeMotionCancel();
4405
4406 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
4407 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
4408}
4409
Garfield Tan1c7bc862020-01-28 13:24:04 -08004410class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
4411protected:
4412 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
4413 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
4414
Chris Yea209fde2020-07-22 13:54:51 -07004415 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004416 sp<FakeWindowHandle> mWindow;
4417
4418 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004419 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08004420 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004421 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004422 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
4423 ASSERT_EQ(OK, mDispatcher->start());
4424
4425 setUpWindow();
4426 }
4427
4428 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07004429 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004430 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004431
Vishnu Nair47074b82020-08-14 11:54:47 -07004432 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004434 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004435 mWindow->consumeFocusEvent(true);
4436 }
4437
Chris Ye2ad95392020-09-01 13:44:44 -07004438 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004439 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004440 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004441 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
4442 mDispatcher->notifyKey(&keyArgs);
4443
4444 // Window should receive key down event.
4445 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4446 }
4447
4448 void expectKeyRepeatOnce(int32_t repeatCount) {
4449 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
4450 InputEvent* repeatEvent = mWindow->consume();
4451 ASSERT_NE(nullptr, repeatEvent);
4452
4453 uint32_t eventType = repeatEvent->getType();
4454 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4455
4456 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4457 uint32_t eventAction = repeatKeyEvent->getAction();
4458 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4459 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4460 }
4461
Chris Ye2ad95392020-09-01 13:44:44 -07004462 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004463 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004464 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004465 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4466 mDispatcher->notifyKey(&keyArgs);
4467
4468 // Window should receive key down event.
4469 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004470 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004471 }
4472};
4473
4474TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00004475 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004476 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4477 expectKeyRepeatOnce(repeatCount);
4478 }
4479}
4480
4481TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00004482 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004483 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4484 expectKeyRepeatOnce(repeatCount);
4485 }
Harry Cutts33476232023-01-30 19:57:29 +00004486 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004487 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004488 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4489 expectKeyRepeatOnce(repeatCount);
4490 }
4491}
4492
4493TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004494 sendAndConsumeKeyDown(/*deviceId=*/1);
4495 expectKeyRepeatOnce(/*repeatCount=*/1);
4496 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004497 mWindow->assertNoEvents();
4498}
4499
4500TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004501 sendAndConsumeKeyDown(/*deviceId=*/1);
4502 expectKeyRepeatOnce(/*repeatCount=*/1);
4503 sendAndConsumeKeyDown(/*deviceId=*/2);
4504 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004505 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00004506 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004507 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00004508 expectKeyRepeatOnce(/*repeatCount=*/2);
4509 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07004510 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00004511 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004512 mWindow->assertNoEvents();
4513}
4514
4515TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004516 sendAndConsumeKeyDown(/*deviceId=*/1);
4517 expectKeyRepeatOnce(/*repeatCount=*/1);
4518 sendAndConsumeKeyDown(/*deviceId=*/2);
4519 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004520 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00004521 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004522 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004523 mWindow->assertNoEvents();
4524}
4525
liushenxiang42232912021-05-21 20:24:09 +08004526TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4527 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00004528 expectKeyRepeatOnce(/*repeatCount=*/1);
4529 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08004530 mDispatcher->notifyDeviceReset(&args);
4531 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4532 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4533 mWindow->assertNoEvents();
4534}
4535
Garfield Tan1c7bc862020-01-28 13:24:04 -08004536TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Harry Cutts33476232023-01-30 19:57:29 +00004537 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004538 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4539 InputEvent* repeatEvent = mWindow->consume();
4540 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4541 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4542 IdGenerator::getSource(repeatEvent->getId()));
4543 }
4544}
4545
4546TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Harry Cutts33476232023-01-30 19:57:29 +00004547 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004548
4549 std::unordered_set<int32_t> idSet;
4550 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4551 InputEvent* repeatEvent = mWindow->consume();
4552 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4553 int32_t id = repeatEvent->getId();
4554 EXPECT_EQ(idSet.end(), idSet.find(id));
4555 idSet.insert(id);
4556 }
4557}
4558
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004559/* Test InputDispatcher for MultiDisplay */
4560class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4561public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004562 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004563 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004564
Chris Yea209fde2020-07-22 13:54:51 -07004565 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004566 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004567 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004568
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004569 // Set focus window for primary display, but focused display would be second one.
4570 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004571 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004573 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004574 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004575
Chris Yea209fde2020-07-22 13:54:51 -07004576 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004577 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004578 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004579 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004580 // Set focus display to second one.
4581 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4582 // Set focus window for second display.
4583 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004584 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004585 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004586 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004587 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004588 }
4589
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004590 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004591 InputDispatcherTest::TearDown();
4592
Chris Yea209fde2020-07-22 13:54:51 -07004593 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004594 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004595 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004596 windowInSecondary.clear();
4597 }
4598
4599protected:
Chris Yea209fde2020-07-22 13:54:51 -07004600 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004601 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004602 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004603 sp<FakeWindowHandle> windowInSecondary;
4604};
4605
4606TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4607 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4609 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4610 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004611 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004612 windowInSecondary->assertNoEvents();
4613
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004614 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4616 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004618 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004619 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004620}
4621
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004622TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004623 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4625 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004627 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004628 windowInSecondary->assertNoEvents();
4629
4630 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004632 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004633 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004634 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004635
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004636 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004637 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004638
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004639 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004640 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4641 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004642
4643 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004644 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004645 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004646 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004647 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004648 windowInSecondary->assertNoEvents();
4649}
4650
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004651// Test per-display input monitors for motion event.
4652TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004653 FakeMonitorReceiver monitorInPrimary =
4654 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4655 FakeMonitorReceiver monitorInSecondary =
4656 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004657
4658 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004662 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004663 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004664 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004665 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004666
4667 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4669 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004671 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004672 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004673 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004674 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004675
4676 // Test inject a non-pointer motion event.
4677 // If specific a display, it will dispatch to the focused window of particular display,
4678 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4680 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004682 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004683 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004684 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004685 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004686}
4687
4688// Test per-display input monitors for key event.
4689TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004690 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004691 FakeMonitorReceiver monitorInPrimary =
4692 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4693 FakeMonitorReceiver monitorInSecondary =
4694 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004695
4696 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4698 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004699 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004700 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004701 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004702 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004703}
4704
Vishnu Nair958da932020-08-21 17:12:37 -07004705TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4706 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004707 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004708 secondWindowInPrimary->setFocusable(true);
4709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4710 setFocusedWindow(secondWindowInPrimary);
4711 windowInPrimary->consumeFocusEvent(false);
4712 secondWindowInPrimary->consumeFocusEvent(true);
4713
4714 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4716 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004717 windowInPrimary->assertNoEvents();
4718 windowInSecondary->assertNoEvents();
4719 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4720}
4721
Arthur Hungdfd528e2021-12-08 13:23:04 +00004722TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4723 FakeMonitorReceiver monitorInPrimary =
4724 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4725 FakeMonitorReceiver monitorInSecondary =
4726 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4727
4728 // Test touch down on primary display.
4729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4730 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4732 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4733 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4734
4735 // Test touch down on second display.
4736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4738 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4739 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4740 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4741
4742 // Trigger cancel touch.
4743 mDispatcher->cancelCurrentTouch();
4744 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4745 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4746 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4747 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4748
4749 // Test inject a move motion event, no window/monitor should receive the event.
4750 ASSERT_EQ(InputEventInjectionResult::FAILED,
4751 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4752 ADISPLAY_ID_DEFAULT, {110, 200}))
4753 << "Inject motion event should return InputEventInjectionResult::FAILED";
4754 windowInPrimary->assertNoEvents();
4755 monitorInPrimary.assertNoEvents();
4756
4757 ASSERT_EQ(InputEventInjectionResult::FAILED,
4758 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4759 SECOND_DISPLAY_ID, {110, 200}))
4760 << "Inject motion event should return InputEventInjectionResult::FAILED";
4761 windowInSecondary->assertNoEvents();
4762 monitorInSecondary.assertNoEvents();
4763}
4764
Jackal Guof9696682018-10-05 12:23:23 +08004765class InputFilterTest : public InputDispatcherTest {
4766protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004767 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4768 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004769 NotifyMotionArgs motionArgs;
4770
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004771 motionArgs =
4772 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004773 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004774 motionArgs =
4775 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004776 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004777 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004778 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004779 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4780 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004781 } else {
4782 mFakePolicy->assertFilterInputEventWasNotCalled();
4783 }
4784 }
4785
4786 void testNotifyKey(bool expectToBeFiltered) {
4787 NotifyKeyArgs keyArgs;
4788
4789 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4790 mDispatcher->notifyKey(&keyArgs);
4791 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4792 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004793 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004794
4795 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004796 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004797 } else {
4798 mFakePolicy->assertFilterInputEventWasNotCalled();
4799 }
4800 }
4801};
4802
4803// Test InputFilter for MotionEvent
4804TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4805 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4806 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4807 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4808
4809 // Enable InputFilter
4810 mDispatcher->setInputFilterEnabled(true);
4811 // Test touch on both primary and second display, and check if both events are filtered.
4812 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4813 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4814
4815 // Disable InputFilter
4816 mDispatcher->setInputFilterEnabled(false);
4817 // Test touch on both primary and second display, and check if both events aren't filtered.
4818 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4819 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4820}
4821
4822// Test InputFilter for KeyEvent
4823TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4824 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4825 testNotifyKey(/*expectToBeFiltered*/ false);
4826
4827 // Enable InputFilter
4828 mDispatcher->setInputFilterEnabled(true);
4829 // Send a key event, and check if it is filtered.
4830 testNotifyKey(/*expectToBeFiltered*/ true);
4831
4832 // Disable InputFilter
4833 mDispatcher->setInputFilterEnabled(false);
4834 // Send a key event, and check if it isn't filtered.
4835 testNotifyKey(/*expectToBeFiltered*/ false);
4836}
4837
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004838// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4839// logical display coordinate space.
4840TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4841 ui::Transform firstDisplayTransform;
4842 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4843 ui::Transform secondDisplayTransform;
4844 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4845
4846 std::vector<gui::DisplayInfo> displayInfos(2);
4847 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4848 displayInfos[0].transform = firstDisplayTransform;
4849 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4850 displayInfos[1].transform = secondDisplayTransform;
4851
4852 mDispatcher->onWindowInfosChanged({}, displayInfos);
4853
4854 // Enable InputFilter
4855 mDispatcher->setInputFilterEnabled(true);
4856
4857 // Ensure the correct transforms are used for the displays.
4858 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4859 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4860}
4861
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004862class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4863protected:
4864 virtual void SetUp() override {
4865 InputDispatcherTest::SetUp();
4866
4867 /**
4868 * We don't need to enable input filter to test the injected event policy, but we enabled it
4869 * here to make the tests more realistic, since this policy only matters when inputfilter is
4870 * on.
4871 */
4872 mDispatcher->setInputFilterEnabled(true);
4873
4874 std::shared_ptr<InputApplicationHandle> application =
4875 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004876 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4877 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004878
4879 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4880 mWindow->setFocusable(true);
4881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4882 setFocusedWindow(mWindow);
4883 mWindow->consumeFocusEvent(true);
4884 }
4885
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004886 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4887 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004888 KeyEvent event;
4889
4890 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4891 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4892 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00004893 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004894 const int32_t additionalPolicyFlags =
4895 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4896 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00004897 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004898 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4899 policyFlags | additionalPolicyFlags));
4900
4901 InputEvent* received = mWindow->consume();
4902 ASSERT_NE(nullptr, received);
4903 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004904 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4905 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4906 ASSERT_EQ(flags, keyEvent.getFlags());
4907 }
4908
4909 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4910 int32_t flags) {
4911 MotionEvent event;
4912 PointerProperties pointerProperties[1];
4913 PointerCoords pointerCoords[1];
4914 pointerProperties[0].clear();
4915 pointerProperties[0].id = 0;
4916 pointerCoords[0].clear();
4917 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4918 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4919
4920 ui::Transform identityTransform;
4921 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4922 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4923 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4924 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4925 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004926 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004927 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004928 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4929
4930 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00004932 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004933 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4934 policyFlags | additionalPolicyFlags));
4935
4936 InputEvent* received = mWindow->consume();
4937 ASSERT_NE(nullptr, received);
4938 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4939 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4940 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4941 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004942 }
4943
4944private:
4945 sp<FakeWindowHandle> mWindow;
4946};
4947
4948TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004949 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4950 // filter. Without it, the event will no different from a regularly injected event, and the
4951 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00004952 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
4953 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004954}
4955
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004956TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004957 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00004958 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004959 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4960}
4961
4962TEST_F(InputFilterInjectionPolicyTest,
4963 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4964 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00004965 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004966 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004967}
4968
4969TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00004970 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
4971 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004972}
4973
chaviwfd6d3512019-03-25 13:23:49 -07004974class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004975 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004976 InputDispatcherTest::SetUp();
4977
Chris Yea209fde2020-07-22 13:54:51 -07004978 std::shared_ptr<FakeApplicationHandle> application =
4979 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004980 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004981 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004982 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004983
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004984 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004985 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004986 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004987
4988 // Set focused application.
4989 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004990 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004991
4992 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004993 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004994 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004995 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004996 }
4997
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004998 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004999 InputDispatcherTest::TearDown();
5000
5001 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005002 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005003 }
5004
5005protected:
5006 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005007 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005008 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005009};
5010
5011// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5012// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5013// the onPointerDownOutsideFocus callback.
5014TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5017 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005019 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005020
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005021 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005022 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5023}
5024
5025// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5026// DOWN on the window that doesn't have focus. Ensure no window received the
5027// onPointerDownOutsideFocus callback.
5028TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005030 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005031 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005032 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005033
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005034 ASSERT_TRUE(mDispatcher->waitForIdle());
5035 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005036}
5037
5038// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5039// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5040TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5042 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005043 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005044 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005045
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005046 ASSERT_TRUE(mDispatcher->waitForIdle());
5047 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005048}
5049
5050// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5051// DOWN on the window that already has focus. Ensure no window received the
5052// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005053TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005055 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005056 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005058 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005059
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005060 ASSERT_TRUE(mDispatcher->waitForIdle());
5061 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005062}
5063
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005064// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5065// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5066TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5067 const MotionEvent event =
5068 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5069 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005070 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005071 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
5072 .build();
5073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
5074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5075 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
5076
5077 ASSERT_TRUE(mDispatcher->waitForIdle());
5078 mFakePolicy->assertOnPointerDownWasNotCalled();
5079 // Ensure that the unfocused window did not receive any FOCUS events.
5080 mUnfocusedWindow->assertNoEvents();
5081}
5082
chaviwaf87b3e2019-10-01 16:59:28 -07005083// These tests ensures we can send touch events to a single client when there are multiple input
5084// windows that point to the same client token.
5085class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
5086 virtual void SetUp() override {
5087 InputDispatcherTest::SetUp();
5088
Chris Yea209fde2020-07-22 13:54:51 -07005089 std::shared_ptr<FakeApplicationHandle> application =
5090 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005091 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
5092 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07005093 mWindow1->setFrame(Rect(0, 0, 100, 100));
5094
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005095 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
5096 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07005097 mWindow2->setFrame(Rect(100, 100, 200, 200));
5098
Arthur Hung72d8dc32020-03-28 00:48:39 +00005099 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07005100 }
5101
5102protected:
5103 sp<FakeWindowHandle> mWindow1;
5104 sp<FakeWindowHandle> mWindow2;
5105
5106 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05005107 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07005108 vec2 vals = windowInfo->transform.transform(point.x, point.y);
5109 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07005110 }
5111
5112 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
5113 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005114 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07005115 InputEvent* event = window->consume();
5116
5117 ASSERT_NE(nullptr, event) << name.c_str()
5118 << ": consumer should have returned non-NULL event.";
5119
5120 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
5121 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
5122 << " event, got " << inputEventTypeToString(event->getType()) << " event";
5123
5124 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005125 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08005126 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07005127
5128 for (size_t i = 0; i < points.size(); i++) {
5129 float expectedX = points[i].x;
5130 float expectedY = points[i].y;
5131
5132 EXPECT_EQ(expectedX, motionEvent.getX(i))
5133 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
5134 << ", got " << motionEvent.getX(i);
5135 EXPECT_EQ(expectedY, motionEvent.getY(i))
5136 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
5137 << ", got " << motionEvent.getY(i);
5138 }
5139 }
chaviw9eaa22c2020-07-01 16:21:27 -07005140
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005141 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07005142 std::vector<PointF> expectedPoints) {
5143 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
5144 ADISPLAY_ID_DEFAULT, touchedPoints);
5145 mDispatcher->notifyMotion(&motionArgs);
5146
5147 // Always consume from window1 since it's the window that has the InputReceiver
5148 consumeMotionEvent(mWindow1, action, expectedPoints);
5149 }
chaviwaf87b3e2019-10-01 16:59:28 -07005150};
5151
5152TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
5153 // Touch Window 1
5154 PointF touchedPoint = {10, 10};
5155 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005156 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005157
5158 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005159 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005160
5161 // Touch Window 2
5162 touchedPoint = {150, 150};
5163 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005164 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005165}
5166
chaviw9eaa22c2020-07-01 16:21:27 -07005167TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
5168 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07005169 mWindow2->setWindowScale(0.5f, 0.5f);
5170
5171 // Touch Window 1
5172 PointF touchedPoint = {10, 10};
5173 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005174 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005175 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005176 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005177
5178 // Touch Window 2
5179 touchedPoint = {150, 150};
5180 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005181 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
5182 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005183
chaviw9eaa22c2020-07-01 16:21:27 -07005184 // Update the transform so rotation is set
5185 mWindow2->setWindowTransform(0, -1, 1, 0);
5186 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
5187 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005188}
5189
chaviw9eaa22c2020-07-01 16:21:27 -07005190TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005191 mWindow2->setWindowScale(0.5f, 0.5f);
5192
5193 // Touch Window 1
5194 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5195 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005196 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005197
5198 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005199 touchedPoints.push_back(PointF{150, 150});
5200 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005201 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005202
chaviw9eaa22c2020-07-01 16:21:27 -07005203 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005204 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005205 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005206
chaviw9eaa22c2020-07-01 16:21:27 -07005207 // Update the transform so rotation is set for Window 2
5208 mWindow2->setWindowTransform(0, -1, 1, 0);
5209 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005210 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005211}
5212
chaviw9eaa22c2020-07-01 16:21:27 -07005213TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005214 mWindow2->setWindowScale(0.5f, 0.5f);
5215
5216 // Touch Window 1
5217 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5218 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005219 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005220
5221 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005222 touchedPoints.push_back(PointF{150, 150});
5223 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005224
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005225 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005226
5227 // Move both windows
5228 touchedPoints = {{20, 20}, {175, 175}};
5229 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5230 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5231
chaviw9eaa22c2020-07-01 16:21:27 -07005232 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005233
chaviw9eaa22c2020-07-01 16:21:27 -07005234 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005235 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005236 expectedPoints.pop_back();
5237
5238 // Touch Window 2
5239 mWindow2->setWindowTransform(0, -1, 1, 0);
5240 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005241 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005242
5243 // Move both windows
5244 touchedPoints = {{20, 20}, {175, 175}};
5245 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5246 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5247
5248 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005249}
5250
5251TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
5252 mWindow1->setWindowScale(0.5f, 0.5f);
5253
5254 // Touch Window 1
5255 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5256 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005257 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005258
5259 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005260 touchedPoints.push_back(PointF{150, 150});
5261 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005262
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005263 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005264
5265 // Move both windows
5266 touchedPoints = {{20, 20}, {175, 175}};
5267 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5268 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5269
chaviw9eaa22c2020-07-01 16:21:27 -07005270 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005271}
5272
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005273class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
5274 virtual void SetUp() override {
5275 InputDispatcherTest::SetUp();
5276
Chris Yea209fde2020-07-22 13:54:51 -07005277 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005278 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005279 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
5280 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005281 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005282 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07005283 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005284
5285 // Set focused application.
5286 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
5287
5288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005289 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005290 mWindow->consumeFocusEvent(true);
5291 }
5292
5293 virtual void TearDown() override {
5294 InputDispatcherTest::TearDown();
5295 mWindow.clear();
5296 }
5297
5298protected:
Chris Yea209fde2020-07-22 13:54:51 -07005299 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005300 sp<FakeWindowHandle> mWindow;
5301 static constexpr PointF WINDOW_LOCATION = {20, 20};
5302
5303 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005305 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5306 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005308 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5309 WINDOW_LOCATION));
5310 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005311
5312 sp<FakeWindowHandle> addSpyWindow() {
5313 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005314 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005315 spy->setTrustedOverlay(true);
5316 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005317 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005318 spy->setDispatchingTimeout(30ms);
5319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
5320 return spy;
5321 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005322};
5323
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005324// Send a tap and respond, which should not cause an ANR.
5325TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
5326 tapOnWindow();
5327 mWindow->consumeMotionDown();
5328 mWindow->consumeMotionUp();
5329 ASSERT_TRUE(mDispatcher->waitForIdle());
5330 mFakePolicy->assertNotifyAnrWasNotCalled();
5331}
5332
5333// Send a regular key and respond, which should not cause an ANR.
5334TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005336 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5337 ASSERT_TRUE(mDispatcher->waitForIdle());
5338 mFakePolicy->assertNotifyAnrWasNotCalled();
5339}
5340
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005341TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
5342 mWindow->setFocusable(false);
5343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5344 mWindow->consumeFocusEvent(false);
5345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005346 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005347 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5348 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
5349 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005351 // Key will not go to window because we have no focused window.
5352 // The 'no focused window' ANR timer should start instead.
5353
5354 // Now, the focused application goes away.
5355 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
5356 // The key should get dropped and there should be no ANR.
5357
5358 ASSERT_TRUE(mDispatcher->waitForIdle());
5359 mFakePolicy->assertNotifyAnrWasNotCalled();
5360}
5361
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005362// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005363// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
5364// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005365TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005367 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5368 WINDOW_LOCATION));
5369
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005370 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
5371 ASSERT_TRUE(sequenceNum);
5372 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005373 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005374
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005375 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005376 mWindow->consumeMotionEvent(
5377 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005378 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005379 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005380}
5381
5382// Send a key to the app and have the app not respond right away.
5383TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
5384 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005386 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
5387 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005388 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005389 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005390 ASSERT_TRUE(mDispatcher->waitForIdle());
5391}
5392
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005393// We have a focused application, but no focused window
5394TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005395 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5397 mWindow->consumeFocusEvent(false);
5398
5399 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5402 WINDOW_LOCATION));
5403 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
5404 mDispatcher->waitForIdle();
5405 mFakePolicy->assertNotifyAnrWasNotCalled();
5406
5407 // Once a focused event arrives, we get an ANR for this application
5408 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5409 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005410 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005411 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5412 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005413 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005414 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07005415 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005416 ASSERT_TRUE(mDispatcher->waitForIdle());
5417}
5418
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005419/**
5420 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
5421 * there will not be an ANR.
5422 */
5423TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
5424 mWindow->setFocusable(false);
5425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5426 mWindow->consumeFocusEvent(false);
5427
5428 KeyEvent event;
5429 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
5430 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
5431
5432 // Define a valid key down event that is stale (too old).
5433 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
5434 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00005435 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005436
5437 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
5438
5439 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005440 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005441 InputEventInjectionSync::WAIT_FOR_RESULT,
5442 INJECT_EVENT_TIMEOUT, policyFlags);
5443 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
5444 << "Injection should fail because the event is stale";
5445
5446 ASSERT_TRUE(mDispatcher->waitForIdle());
5447 mFakePolicy->assertNotifyAnrWasNotCalled();
5448 mWindow->assertNoEvents();
5449}
5450
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005451// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005452// Make sure that we don't notify policy twice about the same ANR.
5453TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005454 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5456 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005457
5458 // Once a focused event arrives, we get an ANR for this application
5459 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5460 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005461 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005462 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5463 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005464 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005465 const std::chrono::duration appTimeout =
5466 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5467 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005468
Vishnu Naire4df8752022-09-08 09:17:55 -07005469 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005470 // ANR should not be raised again. It is up to policy to do that if it desires.
5471 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005472
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005473 // If we now get a focused window, the ANR should stop, but the policy handles that via
5474 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005475 ASSERT_TRUE(mDispatcher->waitForIdle());
5476}
5477
5478// We have a focused application, but no focused window
5479TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005480 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5482 mWindow->consumeFocusEvent(false);
5483
5484 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005485 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005486 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005487 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5488 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005489
Vishnu Naire4df8752022-09-08 09:17:55 -07005490 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5491 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005492
5493 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005494 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005495 ASSERT_TRUE(mDispatcher->waitForIdle());
5496 mWindow->assertNoEvents();
5497}
5498
5499/**
5500 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5501 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5502 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5503 * the ANR mechanism should still work.
5504 *
5505 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5506 * DOWN event, while not responding on the second one.
5507 */
5508TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5509 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5510 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5511 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5512 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5513 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005514 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005515
5516 // Now send ACTION_UP, with identical timestamp
5517 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5518 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5519 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5520 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005521 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005522
5523 // We have now sent down and up. Let's consume first event and then ANR on the second.
5524 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5525 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005526 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005527}
5528
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005529// A spy window can receive an ANR
5530TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5531 sp<FakeWindowHandle> spy = addSpyWindow();
5532
5533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5534 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5535 WINDOW_LOCATION));
5536 mWindow->consumeMotionDown();
5537
5538 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5539 ASSERT_TRUE(sequenceNum);
5540 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005541 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005542
5543 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005544 spy->consumeMotionEvent(
5545 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005546 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005547 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005548}
5549
5550// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005552TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5553 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005554
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005555 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5556 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005558 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005559
5560 // Stuck on the ACTION_UP
5561 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005562 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005563
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005564 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005565 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005566 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5567 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005568
5569 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5570 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005571 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005573 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005574}
5575
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005576// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005577// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005578TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5579 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005580
5581 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005582 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5583 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005584
5585 mWindow->consumeMotionDown();
5586 // Stuck on the ACTION_UP
5587 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005588 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005589
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005590 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005591 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005592 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5593 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005594
5595 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5596 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005597 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005598 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005599 spy->assertNoEvents();
5600}
5601
5602TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5603 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5604
5605 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5606
5607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5608 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5609 WINDOW_LOCATION));
5610
5611 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5612 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5613 ASSERT_TRUE(consumeSeq);
5614
Prabir Pradhanedd96402022-02-15 01:46:16 -08005615 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005616
5617 monitor.finishEvent(*consumeSeq);
5618 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5619
5620 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005621 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622}
5623
5624// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5625// process events, you don't get an anr. When the window later becomes unresponsive again, you
5626// get an ANR again.
5627// 1. tap -> block on ACTION_UP -> receive ANR
5628// 2. consume all pending events (= queue becomes healthy again)
5629// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5630TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5631 tapOnWindow();
5632
5633 mWindow->consumeMotionDown();
5634 // Block on ACTION_UP
5635 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005636 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005637 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5638 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005639 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005640 mWindow->assertNoEvents();
5641
5642 tapOnWindow();
5643 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005644 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005645 mWindow->consumeMotionUp();
5646
5647 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005648 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005649 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005650 mWindow->assertNoEvents();
5651}
5652
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005653// If a connection remains unresponsive for a while, make sure policy is only notified once about
5654// it.
5655TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005656 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005657 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5658 WINDOW_LOCATION));
5659
5660 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005661 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005662 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005663 // 'notifyConnectionUnresponsive' should only be called once per connection
5664 mFakePolicy->assertNotifyAnrWasNotCalled();
5665 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005666 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005667 mWindow->consumeMotionEvent(
5668 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005669 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005670 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005671 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005672 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005673}
5674
5675/**
5676 * If a window is processing a motion event, and then a key event comes in, the key event should
5677 * not to to the focused window until the motion is processed.
5678 *
5679 * Warning!!!
5680 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5681 * and the injection timeout that we specify when injecting the key.
5682 * We must have the injection timeout (10ms) be smaller than
5683 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5684 *
5685 * If that value changes, this test should also change.
5686 */
5687TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5688 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5690
5691 tapOnWindow();
5692 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5693 ASSERT_TRUE(downSequenceNum);
5694 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5695 ASSERT_TRUE(upSequenceNum);
5696 // Don't finish the events yet, and send a key
5697 // Injection will "succeed" because we will eventually give up and send the key to the focused
5698 // window even if motions are still being processed. But because the injection timeout is short,
5699 // we will receive INJECTION_TIMED_OUT as the result.
5700
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005701 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005702 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005703 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5704 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005705 // Key will not be sent to the window, yet, because the window is still processing events
5706 // and the key remains pending, waiting for the touch events to be processed
5707 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5708 ASSERT_FALSE(keySequenceNum);
5709
5710 std::this_thread::sleep_for(500ms);
5711 // if we wait long enough though, dispatcher will give up, and still send the key
5712 // to the focused window, even though we have not yet finished the motion event
5713 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5714 mWindow->finishEvent(*downSequenceNum);
5715 mWindow->finishEvent(*upSequenceNum);
5716}
5717
5718/**
5719 * If a window is processing a motion event, and then a key event comes in, the key event should
5720 * not go to the focused window until the motion is processed.
5721 * If then a new motion comes in, then the pending key event should be going to the currently
5722 * focused window right away.
5723 */
5724TEST_F(InputDispatcherSingleWindowAnr,
5725 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5726 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5728
5729 tapOnWindow();
5730 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5731 ASSERT_TRUE(downSequenceNum);
5732 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5733 ASSERT_TRUE(upSequenceNum);
5734 // Don't finish the events yet, and send a key
5735 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005737 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5738 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005739 // At this point, key is still pending, and should not be sent to the application yet.
5740 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5741 ASSERT_FALSE(keySequenceNum);
5742
5743 // Now tap down again. It should cause the pending key to go to the focused window right away.
5744 tapOnWindow();
5745 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5746 // the other events yet. We can finish events in any order.
5747 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5748 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5749 mWindow->consumeMotionDown();
5750 mWindow->consumeMotionUp();
5751 mWindow->assertNoEvents();
5752}
5753
5754class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5755 virtual void SetUp() override {
5756 InputDispatcherTest::SetUp();
5757
Chris Yea209fde2020-07-22 13:54:51 -07005758 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005759 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005760 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5761 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005762 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005763 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005764 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005765
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005766 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5767 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005768 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005769 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005770
5771 // Set focused application.
5772 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005773 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005774
5775 // Expect one focus window exist in display.
5776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005777 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005778 mFocusedWindow->consumeFocusEvent(true);
5779 }
5780
5781 virtual void TearDown() override {
5782 InputDispatcherTest::TearDown();
5783
5784 mUnfocusedWindow.clear();
5785 mFocusedWindow.clear();
5786 }
5787
5788protected:
Chris Yea209fde2020-07-22 13:54:51 -07005789 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005790 sp<FakeWindowHandle> mUnfocusedWindow;
5791 sp<FakeWindowHandle> mFocusedWindow;
5792 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5793 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5794 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5795
5796 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5797
5798 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5799
5800private:
5801 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5804 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005806 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5807 location));
5808 }
5809};
5810
5811// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5812// should be ANR'd first.
5813TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005815 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5816 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005817 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005818 mFocusedWindow->consumeMotionDown();
5819 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00005820 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005821 // We consumed all events, so no ANR
5822 ASSERT_TRUE(mDispatcher->waitForIdle());
5823 mFakePolicy->assertNotifyAnrWasNotCalled();
5824
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005825 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005826 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5827 FOCUSED_WINDOW_LOCATION));
5828 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5829 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005830
5831 const std::chrono::duration timeout =
5832 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005833 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005834 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5835 // sequence to make it consistent
5836 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005837 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005838 mFocusedWindow->consumeMotionDown();
5839 // This cancel is generated because the connection was unresponsive
5840 mFocusedWindow->consumeMotionCancel();
5841 mFocusedWindow->assertNoEvents();
5842 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005843 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005844 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5845 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005846 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005847}
5848
5849// If we have 2 windows with identical timeouts that are both unresponsive,
5850// it doesn't matter which order they should have ANR.
5851// But we should receive ANR for both.
5852TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5853 // Set the timeout for unfocused window to match the focused window
5854 mUnfocusedWindow->setDispatchingTimeout(10ms);
5855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5856
5857 tapOnFocusedWindow();
5858 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005859 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5860 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5861 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005862
5863 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005864 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5865 mFocusedWindow->getToken() == anrConnectionToken2);
5866 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5867 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005868
5869 ASSERT_TRUE(mDispatcher->waitForIdle());
5870 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005871
5872 mFocusedWindow->consumeMotionDown();
5873 mFocusedWindow->consumeMotionUp();
5874 mUnfocusedWindow->consumeMotionOutside();
5875
Prabir Pradhanedd96402022-02-15 01:46:16 -08005876 sp<IBinder> responsiveToken1, responsiveToken2;
5877 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5878 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005879
5880 // Both applications should be marked as responsive, in any order
5881 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5882 mFocusedWindow->getToken() == responsiveToken2);
5883 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5884 mUnfocusedWindow->getToken() == responsiveToken2);
5885 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886}
5887
5888// If a window is already not responding, the second tap on the same window should be ignored.
5889// We should also log an error to account for the dropped event (not tested here).
5890// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5891TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5892 tapOnFocusedWindow();
5893 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00005894 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 // Receive the events, but don't respond
5896 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5897 ASSERT_TRUE(downEventSequenceNum);
5898 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5899 ASSERT_TRUE(upEventSequenceNum);
5900 const std::chrono::duration timeout =
5901 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005902 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903
5904 // Tap once again
5905 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005906 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005907 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5908 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005909 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005910 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5911 FOCUSED_WINDOW_LOCATION));
5912 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5913 // valid touch target
5914 mUnfocusedWindow->assertNoEvents();
5915
5916 // Consume the first tap
5917 mFocusedWindow->finishEvent(*downEventSequenceNum);
5918 mFocusedWindow->finishEvent(*upEventSequenceNum);
5919 ASSERT_TRUE(mDispatcher->waitForIdle());
5920 // The second tap did not go to the focused window
5921 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005922 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005923 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5924 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005925 mFakePolicy->assertNotifyAnrWasNotCalled();
5926}
5927
5928// If you tap outside of all windows, there will not be ANR
5929TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005930 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005931 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5932 LOCATION_OUTSIDE_ALL_WINDOWS));
5933 ASSERT_TRUE(mDispatcher->waitForIdle());
5934 mFakePolicy->assertNotifyAnrWasNotCalled();
5935}
5936
5937// Since the focused window is paused, tapping on it should not produce any events
5938TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5939 mFocusedWindow->setPaused(true);
5940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5941
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005942 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005943 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5944 FOCUSED_WINDOW_LOCATION));
5945
5946 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5947 ASSERT_TRUE(mDispatcher->waitForIdle());
5948 // Should not ANR because the window is paused, and touches shouldn't go to it
5949 mFakePolicy->assertNotifyAnrWasNotCalled();
5950
5951 mFocusedWindow->assertNoEvents();
5952 mUnfocusedWindow->assertNoEvents();
5953}
5954
5955/**
5956 * If a window is processing a motion event, and then a key event comes in, the key event should
5957 * not to to the focused window until the motion is processed.
5958 * If a different window becomes focused at this time, the key should go to that window instead.
5959 *
5960 * Warning!!!
5961 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5962 * and the injection timeout that we specify when injecting the key.
5963 * We must have the injection timeout (10ms) be smaller than
5964 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5965 *
5966 * If that value changes, this test should also change.
5967 */
5968TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5969 // Set a long ANR timeout to prevent it from triggering
5970 mFocusedWindow->setDispatchingTimeout(2s);
5971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5972
5973 tapOnUnfocusedWindow();
5974 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5975 ASSERT_TRUE(downSequenceNum);
5976 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5977 ASSERT_TRUE(upSequenceNum);
5978 // Don't finish the events yet, and send a key
5979 // Injection will succeed because we will eventually give up and send the key to the focused
5980 // window even if motions are still being processed.
5981
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005982 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005983 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5984 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005986 // Key will not be sent to the window, yet, because the window is still processing events
5987 // and the key remains pending, waiting for the touch events to be processed
5988 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5989 ASSERT_FALSE(keySequenceNum);
5990
5991 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005992 mFocusedWindow->setFocusable(false);
5993 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005995 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005996
5997 // Focus events should precede the key events
5998 mUnfocusedWindow->consumeFocusEvent(true);
5999 mFocusedWindow->consumeFocusEvent(false);
6000
6001 // Finish the tap events, which should unblock dispatcher
6002 mUnfocusedWindow->finishEvent(*downSequenceNum);
6003 mUnfocusedWindow->finishEvent(*upSequenceNum);
6004
6005 // Now that all queues are cleared and no backlog in the connections, the key event
6006 // can finally go to the newly focused "mUnfocusedWindow".
6007 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6008 mFocusedWindow->assertNoEvents();
6009 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006010 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006011}
6012
6013// When the touch stream is split across 2 windows, and one of them does not respond,
6014// then ANR should be raised and the touch should be canceled for the unresponsive window.
6015// The other window should not be affected by that.
6016TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6017 // Touch Window 1
6018 NotifyMotionArgs motionArgs =
6019 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6020 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6021 mDispatcher->notifyMotion(&motionArgs);
6022 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006023 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006024
6025 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006026 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6027 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006028 mDispatcher->notifyMotion(&motionArgs);
6029
6030 const std::chrono::duration timeout =
6031 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006032 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006033
6034 mUnfocusedWindow->consumeMotionDown();
6035 mFocusedWindow->consumeMotionDown();
6036 // Focused window may or may not receive ACTION_MOVE
6037 // But it should definitely receive ACTION_CANCEL due to the ANR
6038 InputEvent* event;
6039 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6040 ASSERT_TRUE(moveOrCancelSequenceNum);
6041 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6042 ASSERT_NE(nullptr, event);
6043 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6044 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6045 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6046 mFocusedWindow->consumeMotionCancel();
6047 } else {
6048 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6049 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006050 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006051 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6052 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006053
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006054 mUnfocusedWindow->assertNoEvents();
6055 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006056 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006057}
6058
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006059/**
6060 * If we have no focused window, and a key comes in, we start the ANR timer.
6061 * The focused application should add a focused window before the timer runs out to prevent ANR.
6062 *
6063 * If the user touches another application during this time, the key should be dropped.
6064 * Next, if a new focused window comes in, without toggling the focused application,
6065 * then no ANR should occur.
6066 *
6067 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6068 * but in some cases the policy may not update the focused application.
6069 */
6070TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6071 std::shared_ptr<FakeApplicationHandle> focusedApplication =
6072 std::make_shared<FakeApplicationHandle>();
6073 focusedApplication->setDispatchingTimeout(60ms);
6074 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
6075 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
6076 mFocusedWindow->setFocusable(false);
6077
6078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6079 mFocusedWindow->consumeFocusEvent(false);
6080
6081 // Send a key. The ANR timer should start because there is no focused window.
6082 // 'focusedApplication' will get blamed if this timer completes.
6083 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006084 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006085 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6086 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6087 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006089
6090 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
6091 // then the injected touches won't cause the focused event to get dropped.
6092 // The dispatcher only checks for whether the queue should be pruned upon queueing.
6093 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
6094 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
6095 // For this test, it means that the key would get delivered to the window once it becomes
6096 // focused.
6097 std::this_thread::sleep_for(10ms);
6098
6099 // Touch unfocused window. This should force the pending key to get dropped.
6100 NotifyMotionArgs motionArgs =
6101 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6102 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
6103 mDispatcher->notifyMotion(&motionArgs);
6104
6105 // We do not consume the motion right away, because that would require dispatcher to first
6106 // process (== drop) the key event, and by that time, ANR will be raised.
6107 // Set the focused window first.
6108 mFocusedWindow->setFocusable(true);
6109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6110 setFocusedWindow(mFocusedWindow);
6111 mFocusedWindow->consumeFocusEvent(true);
6112 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
6113 // to another application. This could be a bug / behaviour in the policy.
6114
6115 mUnfocusedWindow->consumeMotionDown();
6116
6117 ASSERT_TRUE(mDispatcher->waitForIdle());
6118 // Should not ANR because we actually have a focused window. It was just added too slowly.
6119 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
6120}
6121
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006122// These tests ensure we cannot send touch events to a window that's positioned behind a window
6123// that has feature NO_INPUT_CHANNEL.
6124// Layout:
6125// Top (closest to user)
6126// mNoInputWindow (above all windows)
6127// mBottomWindow
6128// Bottom (furthest from user)
6129class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
6130 virtual void SetUp() override {
6131 InputDispatcherTest::SetUp();
6132
6133 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006134 mNoInputWindow =
6135 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6136 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00006137 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006138 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006139 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6140 // It's perfectly valid for this window to not have an associated input channel
6141
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006142 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
6143 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006144 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
6145
6146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6147 }
6148
6149protected:
6150 std::shared_ptr<FakeApplicationHandle> mApplication;
6151 sp<FakeWindowHandle> mNoInputWindow;
6152 sp<FakeWindowHandle> mBottomWindow;
6153};
6154
6155TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
6156 PointF touchedPoint = {10, 10};
6157
6158 NotifyMotionArgs motionArgs =
6159 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6160 ADISPLAY_ID_DEFAULT, {touchedPoint});
6161 mDispatcher->notifyMotion(&motionArgs);
6162
6163 mNoInputWindow->assertNoEvents();
6164 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
6165 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
6166 // and therefore should prevent mBottomWindow from receiving touches
6167 mBottomWindow->assertNoEvents();
6168}
6169
6170/**
6171 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
6172 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
6173 */
6174TEST_F(InputDispatcherMultiWindowOcclusionTests,
6175 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006176 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6177 "Window with input channel and NO_INPUT_CHANNEL",
6178 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006179
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006180 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006181 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6182 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6183
6184 PointF touchedPoint = {10, 10};
6185
6186 NotifyMotionArgs motionArgs =
6187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6188 ADISPLAY_ID_DEFAULT, {touchedPoint});
6189 mDispatcher->notifyMotion(&motionArgs);
6190
6191 mNoInputWindow->assertNoEvents();
6192 mBottomWindow->assertNoEvents();
6193}
6194
Vishnu Nair958da932020-08-21 17:12:37 -07006195class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
6196protected:
6197 std::shared_ptr<FakeApplicationHandle> mApp;
6198 sp<FakeWindowHandle> mWindow;
6199 sp<FakeWindowHandle> mMirror;
6200
6201 virtual void SetUp() override {
6202 InputDispatcherTest::SetUp();
6203 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006204 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6205 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
6206 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07006207 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6208 mWindow->setFocusable(true);
6209 mMirror->setFocusable(true);
6210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6211 }
6212};
6213
6214TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
6215 // Request focus on a mirrored window
6216 setFocusedWindow(mMirror);
6217
6218 // window gets focused
6219 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6221 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006222 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6223}
6224
6225// A focused & mirrored window remains focused only if the window and its mirror are both
6226// focusable.
6227TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
6228 setFocusedWindow(mMirror);
6229
6230 // window gets focused
6231 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6233 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006234 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6236 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006237 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6238
6239 mMirror->setFocusable(false);
6240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6241
6242 // window loses focus since one of the windows associated with the token in not focusable
6243 mWindow->consumeFocusEvent(false);
6244
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006245 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6246 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006247 mWindow->assertNoEvents();
6248}
6249
6250// A focused & mirrored window remains focused until the window and its mirror both become
6251// invisible.
6252TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
6253 setFocusedWindow(mMirror);
6254
6255 // window gets focused
6256 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6258 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006259 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6261 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006262 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6263
6264 mMirror->setVisible(false);
6265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6266
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6268 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006269 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6271 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006272 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6273
6274 mWindow->setVisible(false);
6275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6276
6277 // window loses focus only after all windows associated with the token become invisible.
6278 mWindow->consumeFocusEvent(false);
6279
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006280 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6281 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006282 mWindow->assertNoEvents();
6283}
6284
6285// A focused & mirrored window remains focused until both windows are removed.
6286TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
6287 setFocusedWindow(mMirror);
6288
6289 // window gets focused
6290 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006293 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006296 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6297
6298 // single window is removed but the window token remains focused
6299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
6300
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6302 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006303 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6305 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006306 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6307
6308 // Both windows are removed
6309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
6310 mWindow->consumeFocusEvent(false);
6311
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006312 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6313 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006314 mWindow->assertNoEvents();
6315}
6316
6317// Focus request can be pending until one window becomes visible.
6318TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
6319 // Request focus on an invisible mirror.
6320 mWindow->setVisible(false);
6321 mMirror->setVisible(false);
6322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6323 setFocusedWindow(mMirror);
6324
6325 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006327 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6328 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07006329
6330 mMirror->setVisible(true);
6331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6332
6333 // window gets focused
6334 mWindow->consumeFocusEvent(true);
6335 // window gets the pending key event
6336 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6337}
Prabir Pradhan99987712020-11-10 18:43:05 -08006338
6339class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
6340protected:
6341 std::shared_ptr<FakeApplicationHandle> mApp;
6342 sp<FakeWindowHandle> mWindow;
6343 sp<FakeWindowHandle> mSecondWindow;
6344
6345 void SetUp() override {
6346 InputDispatcherTest::SetUp();
6347 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006348 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006349 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006350 mSecondWindow =
6351 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006352 mSecondWindow->setFocusable(true);
6353
6354 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6356
6357 setFocusedWindow(mWindow);
6358 mWindow->consumeFocusEvent(true);
6359 }
6360
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006361 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
6362 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006363 mDispatcher->notifyPointerCaptureChanged(&args);
6364 }
6365
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006366 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
6367 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006368 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006369 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
6370 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006371 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006372 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08006373 }
6374};
6375
6376TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
6377 // Ensure that capture cannot be obtained for unfocused windows.
6378 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
6379 mFakePolicy->assertSetPointerCaptureNotCalled();
6380 mSecondWindow->assertNoEvents();
6381
6382 // Ensure that capture can be enabled from the focus window.
6383 requestAndVerifyPointerCapture(mWindow, true);
6384
6385 // Ensure that capture cannot be disabled from a window that does not have capture.
6386 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
6387 mFakePolicy->assertSetPointerCaptureNotCalled();
6388
6389 // Ensure that capture can be disabled from the window with capture.
6390 requestAndVerifyPointerCapture(mWindow, false);
6391}
6392
6393TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006394 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006395
6396 setFocusedWindow(mSecondWindow);
6397
6398 // Ensure that the capture disabled event was sent first.
6399 mWindow->consumeCaptureEvent(false);
6400 mWindow->consumeFocusEvent(false);
6401 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006402 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006403
6404 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006405 notifyPointerCaptureChanged({});
6406 notifyPointerCaptureChanged(request);
6407 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08006408 mWindow->assertNoEvents();
6409 mSecondWindow->assertNoEvents();
6410 mFakePolicy->assertSetPointerCaptureNotCalled();
6411}
6412
6413TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006414 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006415
6416 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006417 notifyPointerCaptureChanged({});
6418 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006419
6420 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006421 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006422 mWindow->consumeCaptureEvent(false);
6423 mWindow->assertNoEvents();
6424}
6425
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006426TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
6427 requestAndVerifyPointerCapture(mWindow, true);
6428
6429 // The first window loses focus.
6430 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006431 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006432 mWindow->consumeCaptureEvent(false);
6433
6434 // Request Pointer Capture from the second window before the notification from InputReader
6435 // arrives.
6436 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006437 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006438
6439 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006440 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006441
6442 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006443 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006444
6445 mSecondWindow->consumeFocusEvent(true);
6446 mSecondWindow->consumeCaptureEvent(true);
6447}
6448
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006449TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
6450 // App repeatedly enables and disables capture.
6451 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6452 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6453 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6454 mFakePolicy->assertSetPointerCaptureCalled(false);
6455 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6456 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6457
6458 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6459 // first request is now stale, this should do nothing.
6460 notifyPointerCaptureChanged(firstRequest);
6461 mWindow->assertNoEvents();
6462
6463 // InputReader notifies that the second request was enabled.
6464 notifyPointerCaptureChanged(secondRequest);
6465 mWindow->consumeCaptureEvent(true);
6466}
6467
Prabir Pradhan7092e262022-05-03 16:51:09 +00006468TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6469 requestAndVerifyPointerCapture(mWindow, true);
6470
6471 // App toggles pointer capture off and on.
6472 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6473 mFakePolicy->assertSetPointerCaptureCalled(false);
6474
6475 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6476 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6477
6478 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6479 // preceding "disable" request.
6480 notifyPointerCaptureChanged(enableRequest);
6481
6482 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6483 // any notifications.
6484 mWindow->assertNoEvents();
6485}
6486
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006487class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6488protected:
6489 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006490
6491 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6492 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6493
6494 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6495 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6496
6497 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6498 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6499 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6500 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6501 MAXIMUM_OBSCURING_OPACITY);
6502
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006503 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006504 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006505 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006506
6507 sp<FakeWindowHandle> mTouchWindow;
6508
6509 virtual void SetUp() override {
6510 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006511 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006512 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6513 }
6514
6515 virtual void TearDown() override {
6516 InputDispatcherTest::TearDown();
6517 mTouchWindow.clear();
6518 }
6519
chaviw3277faf2021-05-19 16:45:23 -05006520 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6521 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006522 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006523 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006524 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006525 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006526 return window;
6527 }
6528
6529 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6530 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6531 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006532 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006533 // Generate an arbitrary PID based on the UID
6534 window->setOwnerInfo(1777 + (uid % 10000), uid);
6535 return window;
6536 }
6537
6538 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6539 NotifyMotionArgs args =
6540 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6541 ADISPLAY_ID_DEFAULT, points);
6542 mDispatcher->notifyMotion(&args);
6543 }
6544};
6545
6546TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006547 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006548 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006550
6551 touch();
6552
6553 mTouchWindow->assertNoEvents();
6554}
6555
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006556TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006557 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6558 const sp<FakeWindowHandle>& w =
6559 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6561
6562 touch();
6563
6564 mTouchWindow->assertNoEvents();
6565}
6566
6567TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006568 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6569 const sp<FakeWindowHandle>& w =
6570 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6572
6573 touch();
6574
6575 w->assertNoEvents();
6576}
6577
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006578TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006579 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006581
6582 touch();
6583
6584 mTouchWindow->consumeAnyMotionDown();
6585}
6586
6587TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006588 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006589 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006590 w->setFrame(Rect(0, 0, 50, 50));
6591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006592
6593 touch({PointF{100, 100}});
6594
6595 mTouchWindow->consumeAnyMotionDown();
6596}
6597
6598TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006599 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006600 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6602
6603 touch();
6604
6605 mTouchWindow->consumeAnyMotionDown();
6606}
6607
6608TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6609 const sp<FakeWindowHandle>& w =
6610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006612
6613 touch();
6614
6615 mTouchWindow->consumeAnyMotionDown();
6616}
6617
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006618TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6619 const sp<FakeWindowHandle>& w =
6620 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6622
6623 touch();
6624
6625 w->assertNoEvents();
6626}
6627
6628/**
6629 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6630 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6631 * window, the occluding window will still receive ACTION_OUTSIDE event.
6632 */
6633TEST_F(InputDispatcherUntrustedTouchesTest,
6634 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6635 const sp<FakeWindowHandle>& w =
6636 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006637 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6639
6640 touch();
6641
6642 w->consumeMotionOutside();
6643}
6644
6645TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6646 const sp<FakeWindowHandle>& w =
6647 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006648 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6650
6651 touch();
6652
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006653 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006654}
6655
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006656TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006657 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006658 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6659 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006660 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6661
6662 touch();
6663
6664 mTouchWindow->consumeAnyMotionDown();
6665}
6666
6667TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6668 const sp<FakeWindowHandle>& w =
6669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6670 MAXIMUM_OBSCURING_OPACITY);
6671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006672
6673 touch();
6674
6675 mTouchWindow->consumeAnyMotionDown();
6676}
6677
6678TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006679 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006680 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6681 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6683
6684 touch();
6685
6686 mTouchWindow->assertNoEvents();
6687}
6688
6689TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6690 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6691 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006692 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6693 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006694 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006695 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6696 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6698
6699 touch();
6700
6701 mTouchWindow->assertNoEvents();
6702}
6703
6704TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6705 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6706 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006707 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6708 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006709 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006710 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6711 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6713
6714 touch();
6715
6716 mTouchWindow->consumeAnyMotionDown();
6717}
6718
6719TEST_F(InputDispatcherUntrustedTouchesTest,
6720 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6721 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006722 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6723 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006724 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006725 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6726 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6728
6729 touch();
6730
6731 mTouchWindow->consumeAnyMotionDown();
6732}
6733
6734TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6735 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006736 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6737 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006738 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006739 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6740 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006742
6743 touch();
6744
6745 mTouchWindow->assertNoEvents();
6746}
6747
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006748TEST_F(InputDispatcherUntrustedTouchesTest,
6749 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6750 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006751 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6752 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006753 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006754 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6755 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6757
6758 touch();
6759
6760 mTouchWindow->assertNoEvents();
6761}
6762
6763TEST_F(InputDispatcherUntrustedTouchesTest,
6764 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6765 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006766 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6767 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006768 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006769 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6770 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6772
6773 touch();
6774
6775 mTouchWindow->consumeAnyMotionDown();
6776}
6777
6778TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6779 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006780 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6781 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6783
6784 touch();
6785
6786 mTouchWindow->consumeAnyMotionDown();
6787}
6788
6789TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6790 const sp<FakeWindowHandle>& w =
6791 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6793
6794 touch();
6795
6796 mTouchWindow->consumeAnyMotionDown();
6797}
6798
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006799TEST_F(InputDispatcherUntrustedTouchesTest,
6800 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6801 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6802 const sp<FakeWindowHandle>& w =
6803 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6805
6806 touch();
6807
6808 mTouchWindow->assertNoEvents();
6809}
6810
6811TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6812 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6813 const sp<FakeWindowHandle>& w =
6814 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6816
6817 touch();
6818
6819 mTouchWindow->consumeAnyMotionDown();
6820}
6821
6822TEST_F(InputDispatcherUntrustedTouchesTest,
6823 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6824 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6825 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006826 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6827 OPACITY_ABOVE_THRESHOLD);
6828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6829
6830 touch();
6831
6832 mTouchWindow->consumeAnyMotionDown();
6833}
6834
6835TEST_F(InputDispatcherUntrustedTouchesTest,
6836 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6837 const sp<FakeWindowHandle>& w1 =
6838 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6839 OPACITY_BELOW_THRESHOLD);
6840 const sp<FakeWindowHandle>& w2 =
6841 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6842 OPACITY_BELOW_THRESHOLD);
6843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6844
6845 touch();
6846
6847 mTouchWindow->assertNoEvents();
6848}
6849
6850/**
6851 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6852 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6853 * (which alone would result in allowing touches) does not affect the blocking behavior.
6854 */
6855TEST_F(InputDispatcherUntrustedTouchesTest,
6856 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6857 const sp<FakeWindowHandle>& wB =
6858 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6859 OPACITY_BELOW_THRESHOLD);
6860 const sp<FakeWindowHandle>& wC =
6861 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6862 OPACITY_BELOW_THRESHOLD);
6863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6864
6865 touch();
6866
6867 mTouchWindow->assertNoEvents();
6868}
6869
6870/**
6871 * This test is testing that a window from a different UID but with same application token doesn't
6872 * block the touch. Apps can share the application token for close UI collaboration for example.
6873 */
6874TEST_F(InputDispatcherUntrustedTouchesTest,
6875 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6876 const sp<FakeWindowHandle>& w =
6877 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6878 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6880
6881 touch();
6882
6883 mTouchWindow->consumeAnyMotionDown();
6884}
6885
arthurhungb89ccb02020-12-30 16:19:01 +08006886class InputDispatcherDragTests : public InputDispatcherTest {
6887protected:
6888 std::shared_ptr<FakeApplicationHandle> mApp;
6889 sp<FakeWindowHandle> mWindow;
6890 sp<FakeWindowHandle> mSecondWindow;
6891 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006892 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006893 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6894 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006895
6896 void SetUp() override {
6897 InputDispatcherTest::SetUp();
6898 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006899 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006900 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006901
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006902 mSecondWindow =
6903 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006904 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006905
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006906 mSpyWindow =
6907 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006908 mSpyWindow->setSpy(true);
6909 mSpyWindow->setTrustedOverlay(true);
6910 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6911
arthurhungb89ccb02020-12-30 16:19:01 +08006912 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006914 }
6915
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006916 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6917 switch (fromSource) {
6918 case AINPUT_SOURCE_TOUCHSCREEN:
6919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6920 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6921 ADISPLAY_ID_DEFAULT, {50, 50}))
6922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6923 break;
6924 case AINPUT_SOURCE_STYLUS:
6925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6926 injectMotionEvent(
6927 mDispatcher,
6928 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6929 AINPUT_SOURCE_STYLUS)
6930 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6931 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6932 .x(50)
6933 .y(50))
6934 .build()));
6935 break;
6936 case AINPUT_SOURCE_MOUSE:
6937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6938 injectMotionEvent(
6939 mDispatcher,
6940 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6941 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6942 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6943 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6944 .x(50)
6945 .y(50))
6946 .build()));
6947 break;
6948 default:
6949 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6950 }
arthurhungb89ccb02020-12-30 16:19:01 +08006951
6952 // Window should receive motion event.
6953 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006954 // Spy window should also receive motion event
6955 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006956 }
6957
6958 // Start performing drag, we will create a drag window and transfer touch to it.
6959 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6960 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006961 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006962 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006963 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006964 }
arthurhungb89ccb02020-12-30 16:19:01 +08006965
6966 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006967 mDragWindow =
6968 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006969 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006970 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006971 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006972
6973 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006974 bool transferred =
6975 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00006976 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00006977 if (transferred) {
6978 mWindow->consumeMotionCancel();
6979 mDragWindow->consumeMotionDown();
6980 }
6981 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006982 }
6983};
6984
6985TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006986 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006987
6988 // Move on window.
6989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6990 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6991 ADISPLAY_ID_DEFAULT, {50, 50}))
6992 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6993 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6994 mWindow->consumeDragEvent(false, 50, 50);
6995 mSecondWindow->assertNoEvents();
6996
6997 // Move to another window.
6998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6999 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7000 ADISPLAY_ID_DEFAULT, {150, 50}))
7001 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7002 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7003 mWindow->consumeDragEvent(true, 150, 50);
7004 mSecondWindow->consumeDragEvent(false, 50, 50);
7005
7006 // Move back to original window.
7007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7008 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7009 ADISPLAY_ID_DEFAULT, {50, 50}))
7010 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7011 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7012 mWindow->consumeDragEvent(false, 50, 50);
7013 mSecondWindow->consumeDragEvent(true, -50, 50);
7014
7015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7016 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7018 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7019 mWindow->assertNoEvents();
7020 mSecondWindow->assertNoEvents();
7021}
7022
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007023TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007024 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007025
7026 // No cancel event after drag start
7027 mSpyWindow->assertNoEvents();
7028
7029 const MotionEvent secondFingerDownEvent =
7030 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7031 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007032 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7033 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007034 .build();
7035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7036 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7037 InputEventInjectionSync::WAIT_FOR_RESULT))
7038 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7039
7040 // Receives cancel for first pointer after next pointer down
7041 mSpyWindow->consumeMotionCancel();
7042 mSpyWindow->consumeMotionDown();
7043
7044 mSpyWindow->assertNoEvents();
7045}
7046
arthurhungf452d0b2021-01-06 00:19:52 +08007047TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007048 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007049
7050 // Move on window.
7051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7052 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7053 ADISPLAY_ID_DEFAULT, {50, 50}))
7054 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7055 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7056 mWindow->consumeDragEvent(false, 50, 50);
7057 mSecondWindow->assertNoEvents();
7058
7059 // Move to another window.
7060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7061 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7062 ADISPLAY_ID_DEFAULT, {150, 50}))
7063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7064 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7065 mWindow->consumeDragEvent(true, 150, 50);
7066 mSecondWindow->consumeDragEvent(false, 50, 50);
7067
7068 // drop to another window.
7069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7070 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7071 {150, 50}))
7072 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7073 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7074 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7075 mWindow->assertNoEvents();
7076 mSecondWindow->assertNoEvents();
7077}
7078
arthurhung6d4bed92021-03-17 11:59:33 +08007079TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007080 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08007081
7082 // Move on window and keep button pressed.
7083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7084 injectMotionEvent(mDispatcher,
7085 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7086 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7087 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7088 .x(50)
7089 .y(50))
7090 .build()))
7091 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7092 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7093 mWindow->consumeDragEvent(false, 50, 50);
7094 mSecondWindow->assertNoEvents();
7095
7096 // Move to another window and release button, expect to drop item.
7097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7098 injectMotionEvent(mDispatcher,
7099 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7100 .buttonState(0)
7101 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7102 .x(150)
7103 .y(50))
7104 .build()))
7105 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7106 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7107 mWindow->assertNoEvents();
7108 mSecondWindow->assertNoEvents();
7109 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7110
7111 // nothing to the window.
7112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7113 injectMotionEvent(mDispatcher,
7114 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
7115 .buttonState(0)
7116 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7117 .x(150)
7118 .y(50))
7119 .build()))
7120 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7121 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7122 mWindow->assertNoEvents();
7123 mSecondWindow->assertNoEvents();
7124}
7125
Arthur Hung54745652022-04-20 07:17:41 +00007126TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007127 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08007128
7129 // Set second window invisible.
7130 mSecondWindow->setVisible(false);
7131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
7132
7133 // Move on window.
7134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7135 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7136 ADISPLAY_ID_DEFAULT, {50, 50}))
7137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7138 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7139 mWindow->consumeDragEvent(false, 50, 50);
7140 mSecondWindow->assertNoEvents();
7141
7142 // Move to another window.
7143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7144 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7145 ADISPLAY_ID_DEFAULT, {150, 50}))
7146 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7147 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7148 mWindow->consumeDragEvent(true, 150, 50);
7149 mSecondWindow->assertNoEvents();
7150
7151 // drop to another window.
7152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7153 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7154 {150, 50}))
7155 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7156 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7157 mFakePolicy->assertDropTargetEquals(nullptr);
7158 mWindow->assertNoEvents();
7159 mSecondWindow->assertNoEvents();
7160}
7161
Arthur Hung54745652022-04-20 07:17:41 +00007162TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007163 // Ensure window could track pointerIds if it didn't support split touch.
7164 mWindow->setPreventSplitting(true);
7165
Arthur Hung54745652022-04-20 07:17:41 +00007166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7167 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7168 {50, 50}))
7169 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7170 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7171
7172 const MotionEvent secondFingerDownEvent =
7173 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7174 .displayId(ADISPLAY_ID_DEFAULT)
7175 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007176 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7177 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007178 .build();
7179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7180 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7181 InputEventInjectionSync::WAIT_FOR_RESULT))
7182 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00007183 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00007184
7185 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007186 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007187}
7188
7189TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
7190 // First down on second window.
7191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7192 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7193 {150, 50}))
7194 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7195
7196 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7197
7198 // Second down on first window.
7199 const MotionEvent secondFingerDownEvent =
7200 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7201 .displayId(ADISPLAY_ID_DEFAULT)
7202 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007203 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7204 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007205 .build();
7206 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7207 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7208 InputEventInjectionSync::WAIT_FOR_RESULT))
7209 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7210 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7211
7212 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007213 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007214
7215 // Move on window.
7216 const MotionEvent secondFingerMoveEvent =
7217 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
7218 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007219 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7220 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007221 .build();
7222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7223 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
7224 InputEventInjectionSync::WAIT_FOR_RESULT));
7225 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7226 mWindow->consumeDragEvent(false, 50, 50);
7227 mSecondWindow->consumeMotionMove();
7228
7229 // Release the drag pointer should perform drop.
7230 const MotionEvent secondFingerUpEvent =
7231 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
7232 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007233 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7234 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007235 .build();
7236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7237 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
7238 InputEventInjectionSync::WAIT_FOR_RESULT));
7239 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7240 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
7241 mWindow->assertNoEvents();
7242 mSecondWindow->consumeMotionMove();
7243}
7244
Arthur Hung3915c1f2022-05-31 07:17:17 +00007245TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007246 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00007247
7248 // Update window of second display.
7249 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007250 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00007251 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7252
7253 // Let second display has a touch state.
7254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7255 injectMotionEvent(mDispatcher,
7256 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7257 AINPUT_SOURCE_TOUCHSCREEN)
7258 .displayId(SECOND_DISPLAY_ID)
7259 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7260 .x(100)
7261 .y(100))
7262 .build()));
7263 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00007264 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00007265 // Update window again.
7266 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7267
7268 // Move on window.
7269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7270 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7271 ADISPLAY_ID_DEFAULT, {50, 50}))
7272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7273 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7274 mWindow->consumeDragEvent(false, 50, 50);
7275 mSecondWindow->assertNoEvents();
7276
7277 // Move to another window.
7278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7279 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7280 ADISPLAY_ID_DEFAULT, {150, 50}))
7281 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7282 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7283 mWindow->consumeDragEvent(true, 150, 50);
7284 mSecondWindow->consumeDragEvent(false, 50, 50);
7285
7286 // drop to another window.
7287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7288 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7289 {150, 50}))
7290 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7291 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7292 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7293 mWindow->assertNoEvents();
7294 mSecondWindow->assertNoEvents();
7295}
7296
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007297TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
7298 startDrag(true, AINPUT_SOURCE_MOUSE);
7299 // Move on window.
7300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7301 injectMotionEvent(mDispatcher,
7302 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7303 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7304 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7305 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7306 .x(50)
7307 .y(50))
7308 .build()))
7309 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7310 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7311 mWindow->consumeDragEvent(false, 50, 50);
7312 mSecondWindow->assertNoEvents();
7313
7314 // Move to another window.
7315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7316 injectMotionEvent(mDispatcher,
7317 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7318 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7319 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7320 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7321 .x(150)
7322 .y(50))
7323 .build()))
7324 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7325 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7326 mWindow->consumeDragEvent(true, 150, 50);
7327 mSecondWindow->consumeDragEvent(false, 50, 50);
7328
7329 // drop to another window.
7330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7331 injectMotionEvent(mDispatcher,
7332 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
7333 .buttonState(0)
7334 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7335 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7336 .x(150)
7337 .y(50))
7338 .build()))
7339 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7340 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7341 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7342 mWindow->assertNoEvents();
7343 mSecondWindow->assertNoEvents();
7344}
7345
Vishnu Nair062a8672021-09-03 16:07:44 -07007346class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
7347
7348TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
7349 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007350 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7351 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007352 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007353 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7354 window->setFocusable(true);
7355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7356 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007357 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007358
7359 // With the flag set, window should not get any input
7360 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7361 mDispatcher->notifyKey(&keyArgs);
7362 window->assertNoEvents();
7363
7364 NotifyMotionArgs motionArgs =
7365 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7366 ADISPLAY_ID_DEFAULT);
7367 mDispatcher->notifyMotion(&motionArgs);
7368 window->assertNoEvents();
7369
7370 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007371 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7373
7374 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7375 mDispatcher->notifyKey(&keyArgs);
7376 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7377
7378 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7379 ADISPLAY_ID_DEFAULT);
7380 mDispatcher->notifyMotion(&motionArgs);
7381 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7382 window->assertNoEvents();
7383}
7384
7385TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
7386 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7387 std::make_shared<FakeApplicationHandle>();
7388 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007389 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7390 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007391 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7392 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007393 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007394 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007395 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7396 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007397 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007398 window->setOwnerInfo(222, 222);
7399 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7400 window->setFocusable(true);
7401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7402 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007403 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007404
7405 // With the flag set, window should not get any input
7406 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7407 mDispatcher->notifyKey(&keyArgs);
7408 window->assertNoEvents();
7409
7410 NotifyMotionArgs motionArgs =
7411 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7412 ADISPLAY_ID_DEFAULT);
7413 mDispatcher->notifyMotion(&motionArgs);
7414 window->assertNoEvents();
7415
7416 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007417 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7419
7420 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7421 mDispatcher->notifyKey(&keyArgs);
7422 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7423
7424 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7425 ADISPLAY_ID_DEFAULT);
7426 mDispatcher->notifyMotion(&motionArgs);
7427 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
7428 window->assertNoEvents();
7429}
7430
7431TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
7432 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7433 std::make_shared<FakeApplicationHandle>();
7434 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007435 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7436 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007437 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7438 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007439 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007441 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7442 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007443 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007444 window->setOwnerInfo(222, 222);
7445 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7446 window->setFocusable(true);
7447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7448 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007449 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007450
7451 // With the flag set, window should not get any input
7452 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7453 mDispatcher->notifyKey(&keyArgs);
7454 window->assertNoEvents();
7455
7456 NotifyMotionArgs motionArgs =
7457 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7458 ADISPLAY_ID_DEFAULT);
7459 mDispatcher->notifyMotion(&motionArgs);
7460 window->assertNoEvents();
7461
7462 // When the window is no longer obscured because it went on top, it should get input
7463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7464
7465 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7466 mDispatcher->notifyKey(&keyArgs);
7467 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7468
7469 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7470 ADISPLAY_ID_DEFAULT);
7471 mDispatcher->notifyMotion(&motionArgs);
7472 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7473 window->assertNoEvents();
7474}
7475
Antonio Kantekf16f2832021-09-28 04:39:20 +00007476class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7477protected:
7478 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007479 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007480 sp<FakeWindowHandle> mWindow;
7481 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007482 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007483
7484 void SetUp() override {
7485 InputDispatcherTest::SetUp();
7486
7487 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007488 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007489 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007490 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007491 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007492 mSecondWindow =
7493 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007494 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007495 mThirdWindow =
7496 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7497 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7498 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007499
7500 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7502 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7503 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007504 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007505
Antonio Kantek15beb512022-06-13 22:35:41 +00007506 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007507 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00007508 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007509 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7510 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007511 mThirdWindow->assertNoEvents();
7512 }
7513
7514 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7515 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00007516 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00007517 SECOND_DISPLAY_ID)) {
7518 mWindow->assertNoEvents();
7519 mSecondWindow->assertNoEvents();
7520 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007521 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007522 }
7523
Antonio Kantek15beb512022-06-13 22:35:41 +00007524 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7525 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007526 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7527 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007528 mWindow->consumeTouchModeEvent(inTouchMode);
7529 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007530 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007531 }
7532};
7533
Antonio Kantek26defcf2022-02-08 01:12:27 +00007534TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007535 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007536 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7537 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007538 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007539}
7540
Antonio Kantek26defcf2022-02-08 01:12:27 +00007541TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7542 const WindowInfo& windowInfo = *mWindow->getInfo();
7543 int32_t ownerPid = windowInfo.ownerPid;
7544 int32_t ownerUid = windowInfo.ownerUid;
7545 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7546 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00007547 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07007548 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007549 mWindow->assertNoEvents();
7550 mSecondWindow->assertNoEvents();
7551}
7552
7553TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7554 const WindowInfo& windowInfo = *mWindow->getInfo();
7555 int32_t ownerPid = windowInfo.ownerPid;
7556 int32_t ownerUid = windowInfo.ownerUid;
7557 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007558 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00007559 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007560}
7561
Antonio Kantekf16f2832021-09-28 04:39:20 +00007562TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007563 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007564 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7565 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007566 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007567 mWindow->assertNoEvents();
7568 mSecondWindow->assertNoEvents();
7569}
7570
Antonio Kantek15beb512022-06-13 22:35:41 +00007571TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7572 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7573 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7574 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007575 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00007576 mWindow->assertNoEvents();
7577 mSecondWindow->assertNoEvents();
7578 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7579}
7580
Antonio Kantek48710e42022-03-24 14:19:30 -07007581TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7582 // Interact with the window first.
7583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7584 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7585 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7586
7587 // Then remove focus.
7588 mWindow->setFocusable(false);
7589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7590
7591 // Assert that caller can switch touch mode by owning one of the last interacted window.
7592 const WindowInfo& windowInfo = *mWindow->getInfo();
7593 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7594 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007595 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007596}
7597
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007598class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7599public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007600 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007601 std::shared_ptr<FakeApplicationHandle> application =
7602 std::make_shared<FakeApplicationHandle>();
7603 std::string name = "Fake Spy ";
7604 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007605 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7606 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007607 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007608 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007609 return spy;
7610 }
7611
7612 sp<FakeWindowHandle> createForeground() {
7613 std::shared_ptr<FakeApplicationHandle> application =
7614 std::make_shared<FakeApplicationHandle>();
7615 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007616 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7617 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007618 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007619 return window;
7620 }
7621
7622private:
7623 int mSpyCount{0};
7624};
7625
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007626using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007627/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007628 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7629 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007630TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7631 ScopedSilentDeath _silentDeath;
7632
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007633 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007634 spy->setTrustedOverlay(false);
7635 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7636 ".* not a trusted overlay");
7637}
7638
7639/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007640 * Input injection into a display with a spy window but no foreground windows should succeed.
7641 */
7642TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007643 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7645
7646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7649 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7650}
7651
7652/**
7653 * Verify the order in which different input windows receive events. The touched foreground window
7654 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7655 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7656 * receive events before ones belows it.
7657 *
7658 * Here, we set up a scenario with four windows in the following Z order from the top:
7659 * spy1, spy2, window, spy3.
7660 * We then inject an event and verify that the foreground "window" receives it first, followed by
7661 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7662 * window.
7663 */
7664TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7665 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007666 auto spy1 = createSpy();
7667 auto spy2 = createSpy();
7668 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7670 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7671 const size_t numChannels = channels.size();
7672
Michael Wright8e9a8562022-02-09 13:44:29 +00007673 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007674 if (!epollFd.ok()) {
7675 FAIL() << "Failed to create epoll fd";
7676 }
7677
7678 for (size_t i = 0; i < numChannels; i++) {
7679 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7680 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7681 FAIL() << "Failed to add fd to epoll";
7682 }
7683 }
7684
7685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7686 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7688
7689 std::vector<size_t> eventOrder;
7690 std::vector<struct epoll_event> events(numChannels);
7691 for (;;) {
7692 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7693 (100ms).count());
7694 if (nFds < 0) {
7695 FAIL() << "Failed to call epoll_wait";
7696 }
7697 if (nFds == 0) {
7698 break; // epoll_wait timed out
7699 }
7700 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007701 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007702 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007703 channels[i]->consumeMotionDown();
7704 }
7705 }
7706
7707 // Verify the order in which the events were received.
7708 EXPECT_EQ(3u, eventOrder.size());
7709 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7710 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7711 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7712}
7713
7714/**
7715 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7716 */
7717TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7718 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007719 auto spy = createSpy();
7720 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7722
7723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7724 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7726 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7727 spy->assertNoEvents();
7728}
7729
7730/**
7731 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7732 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7733 * to the window.
7734 */
7735TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7736 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007737 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007738 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7740
7741 // Inject an event outside the spy window's touchable region.
7742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7743 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7744 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7745 window->consumeMotionDown();
7746 spy->assertNoEvents();
7747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7748 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7749 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7750 window->consumeMotionUp();
7751 spy->assertNoEvents();
7752
7753 // Inject an event inside the spy window's touchable region.
7754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7755 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7756 {5, 10}))
7757 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7758 window->consumeMotionDown();
7759 spy->consumeMotionDown();
7760}
7761
7762/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007763 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007764 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007765 */
7766TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7767 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007768 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007769 auto spy = createSpy();
7770 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007771 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007772 spy->setFrame(Rect{0, 0, 20, 20});
7773 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7774
7775 // Inject an event outside the spy window's frame and touchable region.
7776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007777 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7778 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007779 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7780 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007781 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007782}
7783
7784/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007785 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7786 * pointers that are down within its bounds.
7787 */
7788TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7789 auto windowLeft = createForeground();
7790 windowLeft->setFrame({0, 0, 100, 200});
7791 auto windowRight = createForeground();
7792 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007793 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007794 spy->setFrame({0, 0, 200, 200});
7795 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7796
7797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7798 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7799 {50, 50}))
7800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7801 windowLeft->consumeMotionDown();
7802 spy->consumeMotionDown();
7803
7804 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007805 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007806 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007807 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7808 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007809 .build();
7810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7811 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7812 InputEventInjectionSync::WAIT_FOR_RESULT))
7813 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7814 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00007815 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007816}
7817
7818/**
7819 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7820 * the spy should receive the second pointer with ACTION_DOWN.
7821 */
7822TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7823 auto window = createForeground();
7824 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007825 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007826 spyRight->setFrame({100, 0, 200, 200});
7827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7828
7829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7830 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7831 {50, 50}))
7832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7833 window->consumeMotionDown();
7834 spyRight->assertNoEvents();
7835
7836 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007837 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007838 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007839 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7840 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007841 .build();
7842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7843 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7844 InputEventInjectionSync::WAIT_FOR_RESULT))
7845 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00007846 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007847 spyRight->consumeMotionDown();
7848}
7849
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007850/**
7851 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7852 * windows should be allowed to control split touch.
7853 */
7854TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007855 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007856 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007857 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007858 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007859
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007860 auto window = createForeground();
7861 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007862
7863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7864
7865 // First finger down, no window touched.
7866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7868 {100, 200}))
7869 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7870 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7871 window->assertNoEvents();
7872
7873 // Second finger down on window, the window should receive touch down.
7874 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007875 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007876 .displayId(ADISPLAY_ID_DEFAULT)
7877 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007878 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
7879 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007880 .build();
7881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7882 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7883 InputEventInjectionSync::WAIT_FOR_RESULT))
7884 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7885
7886 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00007887 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007888}
7889
7890/**
7891 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7892 * do not receive key events.
7893 */
7894TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007895 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007896 spy->setFocusable(false);
7897
7898 auto window = createForeground();
7899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7900 setFocusedWindow(window);
7901 window->consumeFocusEvent(true);
7902
7903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7904 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7905 window->consumeKeyDown(ADISPLAY_ID_NONE);
7906
7907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7908 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7909 window->consumeKeyUp(ADISPLAY_ID_NONE);
7910
7911 spy->assertNoEvents();
7912}
7913
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007914using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7915
7916/**
7917 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7918 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7919 */
7920TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7921 auto window = createForeground();
7922 auto spy1 = createSpy();
7923 auto spy2 = createSpy();
7924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7925
7926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7927 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7929 window->consumeMotionDown();
7930 spy1->consumeMotionDown();
7931 spy2->consumeMotionDown();
7932
7933 // Pilfer pointers from the second spy window.
7934 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7935 spy2->assertNoEvents();
7936 spy1->consumeMotionCancel();
7937 window->consumeMotionCancel();
7938
7939 // The rest of the gesture should only be sent to the second spy window.
7940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7941 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7942 ADISPLAY_ID_DEFAULT))
7943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7944 spy2->consumeMotionMove();
7945 spy1->assertNoEvents();
7946 window->assertNoEvents();
7947}
7948
7949/**
7950 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7951 * in the middle of the gesture.
7952 */
7953TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7954 auto window = createForeground();
7955 auto spy = createSpy();
7956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7957
7958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7960 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7961 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7962 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7963
7964 window->releaseChannel();
7965
7966 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7967
7968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7969 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7970 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7971 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7972}
7973
7974/**
7975 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7976 * the spy, but not to any other windows.
7977 */
7978TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7979 auto spy = createSpy();
7980 auto window = createForeground();
7981
7982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7983
7984 // First finger down on the window and the spy.
7985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7986 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7987 {100, 200}))
7988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7989 spy->consumeMotionDown();
7990 window->consumeMotionDown();
7991
7992 // Spy window pilfers the pointers.
7993 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7994 window->consumeMotionCancel();
7995
7996 // Second finger down on the window and spy, but the window should not receive the pointer down.
7997 const MotionEvent secondFingerDownEvent =
7998 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7999 .displayId(ADISPLAY_ID_DEFAULT)
8000 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008001 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8002 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008003 .build();
8004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8005 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8006 InputEventInjectionSync::WAIT_FOR_RESULT))
8007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8008
Harry Cutts33476232023-01-30 19:57:29 +00008009 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008010
8011 // Third finger goes down outside all windows, so injection should fail.
8012 const MotionEvent thirdFingerDownEvent =
8013 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8014 .displayId(ADISPLAY_ID_DEFAULT)
8015 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008016 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8017 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8018 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008019 .build();
8020 ASSERT_EQ(InputEventInjectionResult::FAILED,
8021 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8022 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008023 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008024
8025 spy->assertNoEvents();
8026 window->assertNoEvents();
8027}
8028
8029/**
8030 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8031 */
8032TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8033 auto spy = createSpy();
8034 spy->setFrame(Rect(0, 0, 100, 100));
8035 auto window = createForeground();
8036 window->setFrame(Rect(0, 0, 200, 200));
8037
8038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8039
8040 // First finger down on the window only
8041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8042 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8043 {150, 150}))
8044 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8045 window->consumeMotionDown();
8046
8047 // Second finger down on the spy and window
8048 const MotionEvent secondFingerDownEvent =
8049 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8050 .displayId(ADISPLAY_ID_DEFAULT)
8051 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008052 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8053 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008054 .build();
8055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8056 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8057 InputEventInjectionSync::WAIT_FOR_RESULT))
8058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8059 spy->consumeMotionDown();
8060 window->consumeMotionPointerDown(1);
8061
8062 // Third finger down on the spy and window
8063 const MotionEvent thirdFingerDownEvent =
8064 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8065 .displayId(ADISPLAY_ID_DEFAULT)
8066 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008067 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8068 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8069 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008070 .build();
8071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8072 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8073 InputEventInjectionSync::WAIT_FOR_RESULT))
8074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8075 spy->consumeMotionPointerDown(1);
8076 window->consumeMotionPointerDown(2);
8077
8078 // Spy window pilfers the pointers.
8079 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8080 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8081 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8082
8083 spy->assertNoEvents();
8084 window->assertNoEvents();
8085}
8086
8087/**
8088 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
8089 * other windows should be canceled. If this results in the cancellation of all pointers for some
8090 * window, then that window should receive ACTION_CANCEL.
8091 */
8092TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
8093 auto spy = createSpy();
8094 spy->setFrame(Rect(0, 0, 100, 100));
8095 auto window = createForeground();
8096 window->setFrame(Rect(0, 0, 200, 200));
8097
8098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8099
8100 // First finger down on both spy and window
8101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8102 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8103 {10, 10}))
8104 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8105 window->consumeMotionDown();
8106 spy->consumeMotionDown();
8107
8108 // Second finger down on the spy and window
8109 const MotionEvent secondFingerDownEvent =
8110 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8111 .displayId(ADISPLAY_ID_DEFAULT)
8112 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008113 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8114 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008115 .build();
8116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8117 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8118 InputEventInjectionSync::WAIT_FOR_RESULT))
8119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8120 spy->consumeMotionPointerDown(1);
8121 window->consumeMotionPointerDown(1);
8122
8123 // Spy window pilfers the pointers.
8124 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8125 window->consumeMotionCancel();
8126
8127 spy->assertNoEvents();
8128 window->assertNoEvents();
8129}
8130
8131/**
8132 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
8133 * be sent to other windows
8134 */
8135TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
8136 auto spy = createSpy();
8137 spy->setFrame(Rect(0, 0, 100, 100));
8138 auto window = createForeground();
8139 window->setFrame(Rect(0, 0, 200, 200));
8140
8141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8142
8143 // First finger down on both window and spy
8144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8145 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8146 {10, 10}))
8147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8148 window->consumeMotionDown();
8149 spy->consumeMotionDown();
8150
8151 // Spy window pilfers the pointers.
8152 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8153 window->consumeMotionCancel();
8154
8155 // Second finger down on the window only
8156 const MotionEvent secondFingerDownEvent =
8157 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8158 .displayId(ADISPLAY_ID_DEFAULT)
8159 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008160 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8161 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008162 .build();
8163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8164 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8165 InputEventInjectionSync::WAIT_FOR_RESULT))
8166 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8167 window->consumeMotionDown();
8168 window->assertNoEvents();
8169
8170 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
8171 spy->consumeMotionMove();
8172 spy->assertNoEvents();
8173}
8174
Prabir Pradhand65552b2021-10-07 11:23:50 -07008175class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
8176public:
8177 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
8178 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8179 std::make_shared<FakeApplicationHandle>();
8180 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008181 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
8182 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008183 overlay->setFocusable(false);
8184 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008185 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008186 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008187 overlay->setTrustedOverlay(true);
8188
8189 std::shared_ptr<FakeApplicationHandle> application =
8190 std::make_shared<FakeApplicationHandle>();
8191 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008192 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
8193 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008194 window->setFocusable(true);
8195 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008196
8197 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8199 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008200 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008201 return {std::move(overlay), std::move(window)};
8202 }
8203
8204 void sendFingerEvent(int32_t action) {
8205 NotifyMotionArgs motionArgs =
8206 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8207 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
8208 mDispatcher->notifyMotion(&motionArgs);
8209 }
8210
8211 void sendStylusEvent(int32_t action) {
8212 NotifyMotionArgs motionArgs =
8213 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8214 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
8215 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
8216 mDispatcher->notifyMotion(&motionArgs);
8217 }
8218};
8219
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008220using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
8221
8222TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
8223 ScopedSilentDeath _silentDeath;
8224
Prabir Pradhand65552b2021-10-07 11:23:50 -07008225 auto [overlay, window] = setupStylusOverlayScenario();
8226 overlay->setTrustedOverlay(false);
8227 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
8228 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
8229 ".* not a trusted overlay");
8230}
8231
8232TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
8233 auto [overlay, window] = setupStylusOverlayScenario();
8234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8235
8236 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8237 overlay->consumeMotionDown();
8238 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8239 overlay->consumeMotionUp();
8240
8241 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8242 window->consumeMotionDown();
8243 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8244 window->consumeMotionUp();
8245
8246 overlay->assertNoEvents();
8247 window->assertNoEvents();
8248}
8249
8250TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
8251 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008252 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8254
8255 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8256 overlay->consumeMotionDown();
8257 window->consumeMotionDown();
8258 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8259 overlay->consumeMotionUp();
8260 window->consumeMotionUp();
8261
8262 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8263 window->consumeMotionDown();
8264 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8265 window->consumeMotionUp();
8266
8267 overlay->assertNoEvents();
8268 window->assertNoEvents();
8269}
8270
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00008271/**
8272 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
8273 * The scenario is as follows:
8274 * - The stylus interceptor overlay is configured as a spy window.
8275 * - The stylus interceptor spy receives the start of a new stylus gesture.
8276 * - It pilfers pointers and then configures itself to no longer be a spy.
8277 * - The stylus interceptor continues to receive the rest of the gesture.
8278 */
8279TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
8280 auto [overlay, window] = setupStylusOverlayScenario();
8281 overlay->setSpy(true);
8282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8283
8284 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8285 overlay->consumeMotionDown();
8286 window->consumeMotionDown();
8287
8288 // The interceptor pilfers the pointers.
8289 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
8290 window->consumeMotionCancel();
8291
8292 // The interceptor configures itself so that it is no longer a spy.
8293 overlay->setSpy(false);
8294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8295
8296 // It continues to receive the rest of the stylus gesture.
8297 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
8298 overlay->consumeMotionMove();
8299 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8300 overlay->consumeMotionUp();
8301
8302 window->assertNoEvents();
8303}
8304
Prabir Pradhan5735a322022-04-11 17:23:34 +00008305struct User {
8306 int32_t mPid;
8307 int32_t mUid;
8308 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
8309 std::unique_ptr<InputDispatcher>& mDispatcher;
8310
8311 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
8312 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
8313
8314 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
8315 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
8316 ADISPLAY_ID_DEFAULT, {100, 200},
8317 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
8318 AMOTION_EVENT_INVALID_CURSOR_POSITION},
8319 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
8320 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
8321 }
8322
8323 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00008324 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00008325 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00008326 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00008327 mPolicyFlags);
8328 }
8329
8330 sp<FakeWindowHandle> createWindow() const {
8331 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8332 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008333 sp<FakeWindowHandle> window =
8334 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
8335 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00008336 window->setOwnerInfo(mPid, mUid);
8337 return window;
8338 }
8339};
8340
8341using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
8342
8343TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
8344 auto owner = User(mDispatcher, 10, 11);
8345 auto window = owner.createWindow();
8346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8347
8348 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8349 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8350 window->consumeMotionDown();
8351
8352 setFocusedWindow(window);
8353 window->consumeFocusEvent(true);
8354
8355 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8356 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8357 window->consumeKeyDown(ADISPLAY_ID_NONE);
8358}
8359
8360TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
8361 auto owner = User(mDispatcher, 10, 11);
8362 auto window = owner.createWindow();
8363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8364
8365 auto rando = User(mDispatcher, 20, 21);
8366 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8367 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8368
8369 setFocusedWindow(window);
8370 window->consumeFocusEvent(true);
8371
8372 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8373 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8374 window->assertNoEvents();
8375}
8376
8377TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
8378 auto owner = User(mDispatcher, 10, 11);
8379 auto window = owner.createWindow();
8380 auto spy = owner.createWindow();
8381 spy->setSpy(true);
8382 spy->setTrustedOverlay(true);
8383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8384
8385 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8386 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8387 spy->consumeMotionDown();
8388 window->consumeMotionDown();
8389}
8390
8391TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
8392 auto owner = User(mDispatcher, 10, 11);
8393 auto window = owner.createWindow();
8394
8395 auto rando = User(mDispatcher, 20, 21);
8396 auto randosSpy = rando.createWindow();
8397 randosSpy->setSpy(true);
8398 randosSpy->setTrustedOverlay(true);
8399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8400
8401 // The event is targeted at owner's window, so injection should succeed, but the spy should
8402 // not receive the event.
8403 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8404 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8405 randosSpy->assertNoEvents();
8406 window->consumeMotionDown();
8407}
8408
8409TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
8410 auto owner = User(mDispatcher, 10, 11);
8411 auto window = owner.createWindow();
8412
8413 auto rando = User(mDispatcher, 20, 21);
8414 auto randosSpy = rando.createWindow();
8415 randosSpy->setSpy(true);
8416 randosSpy->setTrustedOverlay(true);
8417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8418
8419 // A user that has injection permission can inject into any window.
8420 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8421 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8422 ADISPLAY_ID_DEFAULT));
8423 randosSpy->consumeMotionDown();
8424 window->consumeMotionDown();
8425
8426 setFocusedWindow(randosSpy);
8427 randosSpy->consumeFocusEvent(true);
8428
8429 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
8430 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
8431 window->assertNoEvents();
8432}
8433
8434TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
8435 auto owner = User(mDispatcher, 10, 11);
8436 auto window = owner.createWindow();
8437
8438 auto rando = User(mDispatcher, 20, 21);
8439 auto randosWindow = rando.createWindow();
8440 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8441 randosWindow->setWatchOutsideTouch(true);
8442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8443
8444 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8445 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8446 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8447 window->consumeMotionDown();
8448 randosWindow->consumeMotionOutside();
8449}
8450
Garfield Tane84e6f92019-08-29 17:28:41 -07008451} // namespace android::inputdispatcher