blob: d3d39b9a2867073ca397ec83b8518e3cdc89f2ed [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 Vishniakou5bf25d92023-02-08 15:43:38 -08001570class MotionArgsBuilder {
1571public:
1572 MotionArgsBuilder(int32_t action, int32_t source) {
1573 mAction = action;
1574 mSource = source;
1575 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1576 mDownTime = mEventTime;
1577 }
1578
1579 MotionArgsBuilder& deviceId(int32_t deviceId) {
1580 mDeviceId = deviceId;
1581 return *this;
1582 }
1583
1584 MotionArgsBuilder& downTime(nsecs_t downTime) {
1585 mDownTime = downTime;
1586 return *this;
1587 }
1588
1589 MotionArgsBuilder& eventTime(nsecs_t eventTime) {
1590 mEventTime = eventTime;
1591 return *this;
1592 }
1593
1594 MotionArgsBuilder& displayId(int32_t displayId) {
1595 mDisplayId = displayId;
1596 return *this;
1597 }
1598
1599 MotionArgsBuilder& policyFlags(int32_t policyFlags) {
1600 mPolicyFlags = policyFlags;
1601 return *this;
1602 }
1603
1604 MotionArgsBuilder& actionButton(int32_t actionButton) {
1605 mActionButton = actionButton;
1606 return *this;
1607 }
1608
1609 MotionArgsBuilder& buttonState(int32_t buttonState) {
1610 mButtonState = buttonState;
1611 return *this;
1612 }
1613
1614 MotionArgsBuilder& rawXCursorPosition(float rawXCursorPosition) {
1615 mRawXCursorPosition = rawXCursorPosition;
1616 return *this;
1617 }
1618
1619 MotionArgsBuilder& rawYCursorPosition(float rawYCursorPosition) {
1620 mRawYCursorPosition = rawYCursorPosition;
1621 return *this;
1622 }
1623
1624 MotionArgsBuilder& pointer(PointerBuilder pointer) {
1625 mPointers.push_back(pointer);
1626 return *this;
1627 }
1628
1629 MotionArgsBuilder& addFlag(uint32_t flags) {
1630 mFlags |= flags;
1631 return *this;
1632 }
1633
1634 NotifyMotionArgs build() {
1635 std::vector<PointerProperties> pointerProperties;
1636 std::vector<PointerCoords> pointerCoords;
1637 for (const PointerBuilder& pointer : mPointers) {
1638 pointerProperties.push_back(pointer.buildProperties());
1639 pointerCoords.push_back(pointer.buildCoords());
1640 }
1641
1642 // Set mouse cursor position for the most common cases to avoid boilerplate.
1643 if (mSource == AINPUT_SOURCE_MOUSE &&
1644 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1645 mPointers.size() == 1) {
1646 mRawXCursorPosition = pointerCoords[0].getX();
1647 mRawYCursorPosition = pointerCoords[0].getY();
1648 }
1649
1650 NotifyMotionArgs args(InputEvent::nextId(), mEventTime, /*readTime=*/mEventTime, mDeviceId,
1651 mSource, mDisplayId, mPolicyFlags, mAction, mActionButton, mFlags,
1652 AMETA_NONE, mButtonState, MotionClassification::NONE, /*edgeFlags=*/0,
1653 mPointers.size(), pointerProperties.data(), pointerCoords.data(),
1654 /*xPrecision=*/0, /*yPrecision=*/0, mRawXCursorPosition,
1655 mRawYCursorPosition, mDownTime, /*videoFrames=*/{});
1656
1657 return args;
1658 }
1659
1660private:
1661 int32_t mAction;
1662 int32_t mDeviceId = DEVICE_ID;
1663 int32_t mSource;
1664 nsecs_t mDownTime;
1665 nsecs_t mEventTime;
1666 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1667 int32_t mPolicyFlags = DEFAULT_POLICY_FLAGS;
1668 int32_t mActionButton{0};
1669 int32_t mButtonState{0};
1670 int32_t mFlags{0};
1671 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1672 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1673
1674 std::vector<PointerBuilder> mPointers;
1675};
1676
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001678 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001679 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001680 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1681 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1682 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1683 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001684}
1685
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001686static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001687 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001688 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001689 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001690 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1691 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001692 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001693 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1694 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001695 MotionEvent event = MotionEventBuilder(action, source)
1696 .displayId(displayId)
1697 .eventTime(eventTime)
1698 .rawXCursorPosition(cursorPosition.x)
1699 .rawYCursorPosition(cursorPosition.y)
Harry Cutts33476232023-01-30 19:57:29 +00001700 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Garfield Tandf26e862020-07-01 20:18:19 -07001701 .x(position.x)
1702 .y(position.y))
1703 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001704
1705 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001706 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1707 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001708}
1709
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001710static InputEventInjectionResult injectMotionDown(
1711 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1712 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001713 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001714}
1715
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001716static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 int32_t source, int32_t displayId,
1718 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001719 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001720}
1721
Jackal Guof9696682018-10-05 12:23:23 +08001722static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1723 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1724 // Define a valid key event.
Harry Cutts33476232023-01-30 19:57:29 +00001725 NotifyKeyArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001726 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1727 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001728
1729 return args;
1730}
1731
chaviwd1c23182019-12-20 18:44:56 -08001732static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1733 const std::vector<PointF>& points) {
1734 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001735 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1736 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1737 }
1738
chaviwd1c23182019-12-20 18:44:56 -08001739 PointerProperties pointerProperties[pointerCount];
1740 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001741
chaviwd1c23182019-12-20 18:44:56 -08001742 for (size_t i = 0; i < pointerCount; i++) {
1743 pointerProperties[i].clear();
1744 pointerProperties[i].id = i;
1745 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001746
chaviwd1c23182019-12-20 18:44:56 -08001747 pointerCoords[i].clear();
1748 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1749 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1750 }
Jackal Guof9696682018-10-05 12:23:23 +08001751
1752 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1753 // Define a valid motion event.
Harry Cutts33476232023-01-30 19:57:29 +00001754 NotifyMotionArgs args(/*id=*/0, currentTime, /*readTime=*/0, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001755 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1756 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001757 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1758 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001759 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1760 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001761
1762 return args;
1763}
1764
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001765static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1766 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1767}
1768
chaviwd1c23182019-12-20 18:44:56 -08001769static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1770 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1771}
1772
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001773static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1774 const PointerCaptureRequest& request) {
Harry Cutts33476232023-01-30 19:57:29 +00001775 return NotifyPointerCaptureChangedArgs(/*id=*/0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001776}
1777
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001778/**
1779 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1780 * broken channel.
1781 */
1782TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1783 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1784 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001785 sp<FakeWindowHandle>::make(application, mDispatcher,
1786 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001787
1788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1789
1790 // Window closes its channel, but the window remains.
1791 window->destroyReceiver();
1792 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1793}
1794
Arthur Hungb92218b2018-08-14 12:00:21 +08001795TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001797 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1798 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001799
Arthur Hung72d8dc32020-03-28 00:48:39 +00001800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1802 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1803 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001804
1805 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001806 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001807}
1808
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001809TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001811 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1812 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001813
1814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1815 // Inject a MotionEvent to an unknown display.
1816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1817 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1819
1820 // Window should receive motion event.
1821 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1822}
1823
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001824/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001825 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001826 * This test serves as a sanity check for the next test, where setInputWindows is
1827 * called twice.
1828 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001829TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001830 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001831 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1832 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001833 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001834
1835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1838 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001840
1841 // Window should receive motion event.
1842 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1843}
1844
1845/**
1846 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001847 */
1848TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001849 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001850 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1851 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001852 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001853
1854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001857 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1858 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001860
1861 // Window should receive motion event.
1862 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1863}
1864
Arthur Hungb92218b2018-08-14 12:00:21 +08001865// The foreground window should receive the first touch down event.
1866TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001868 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001869 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001870 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001871 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001872
Arthur Hung72d8dc32020-03-28 00:48:39 +00001873 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1875 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1876 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001877
1878 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001879 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001880 windowSecond->assertNoEvents();
1881}
1882
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001883/**
1884 * Two windows: A top window, and a wallpaper behind the window.
1885 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1886 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001887 * 1. foregroundWindow <-- dup touch to wallpaper
1888 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001889 */
1890TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1891 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1892 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001893 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001894 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001895 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001896 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001897 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001898
1899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1902 {100, 200}))
1903 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1904
1905 // Both foreground window and its wallpaper should receive the touch down
1906 foregroundWindow->consumeMotionDown();
1907 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1908
1909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1910 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1911 ADISPLAY_ID_DEFAULT, {110, 200}))
1912 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1913
1914 foregroundWindow->consumeMotionMove();
1915 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1916
1917 // Now the foreground window goes away, but the wallpaper stays
1918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1919 foregroundWindow->consumeMotionCancel();
1920 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1921 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1922}
1923
1924/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001925 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1926 * with the following differences:
1927 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1928 * clean up the connection.
1929 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1930 * Ensure that there's no crash in the dispatcher.
1931 */
1932TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1933 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1934 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001935 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001936 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001937 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001938 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001939 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001940
1941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1943 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1944 {100, 200}))
1945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1946
1947 // Both foreground window and its wallpaper should receive the touch down
1948 foregroundWindow->consumeMotionDown();
1949 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1950
1951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1952 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1953 ADISPLAY_ID_DEFAULT, {110, 200}))
1954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1955
1956 foregroundWindow->consumeMotionMove();
1957 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1958
1959 // Wallpaper closes its channel, but the window remains.
1960 wallpaperWindow->destroyReceiver();
1961 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1962
1963 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1964 // is no longer valid.
1965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1966 foregroundWindow->consumeMotionCancel();
1967}
1968
Arthur Hungc539dbb2022-12-08 07:45:36 +00001969class ShouldSplitTouchFixture : public InputDispatcherTest,
1970 public ::testing::WithParamInterface<bool> {};
1971INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1972 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001973/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001974 * A single window that receives touch (on top), and a wallpaper window underneath it.
1975 * The top window gets a multitouch gesture.
1976 * Ensure that wallpaper gets the same gesture.
1977 */
Arthur Hungc539dbb2022-12-08 07:45:36 +00001978TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001979 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00001980 sp<FakeWindowHandle> foregroundWindow =
1981 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1982 foregroundWindow->setDupTouchToWallpaper(true);
1983 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001984
1985 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001986 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001987 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001988
Arthur Hungc539dbb2022-12-08 07:45:36 +00001989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001990
1991 // Touch down on top window
1992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1993 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1994 {100, 100}))
1995 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1996
1997 // Both top window and its wallpaper should receive the touch down
Arthur Hungc539dbb2022-12-08 07:45:36 +00001998 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001999 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2000
2001 // Second finger down on the top window
2002 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002003 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002004 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002005 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2006 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002007 .build();
2008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2009 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2010 InputEventInjectionSync::WAIT_FOR_RESULT))
2011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2012
Harry Cutts33476232023-01-30 19:57:29 +00002013 foregroundWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
2014 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002015 expectedWallpaperFlags);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002016
2017 const MotionEvent secondFingerUpEvent =
2018 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
2019 .displayId(ADISPLAY_ID_DEFAULT)
2020 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002021 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2022 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Arthur Hungc539dbb2022-12-08 07:45:36 +00002023 .build();
2024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2025 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
2026 InputEventInjectionSync::WAIT_FOR_RESULT))
2027 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2028 foregroundWindow->consumeMotionPointerUp(0);
2029 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2030
2031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2032 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2033 {100, 100}))
2034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2035 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2036 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002037}
2038
2039/**
2040 * Two windows: a window on the left and window on the right.
2041 * A third window, wallpaper, is behind both windows, and spans both top windows.
2042 * The first touch down goes to the left window. A second pointer touches down on the right window.
2043 * The touch is split, so both left and right windows should receive ACTION_DOWN.
2044 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
2045 * ACTION_POINTER_DOWN(1).
2046 */
2047TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
2048 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2049 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002050 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002051 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002052 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002053
2054 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002055 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002056 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002057 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002058
2059 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002060 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002061 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002062 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002063
2064 mDispatcher->setInputWindows(
2065 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
2066
2067 // Touch down on left window
2068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2069 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2070 {100, 100}))
2071 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2072
2073 // Both foreground window and its wallpaper should receive the touch down
2074 leftWindow->consumeMotionDown();
2075 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2076
2077 // Second finger down on the right window
2078 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002079 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002080 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002081 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2082 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(300).y(100))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002083 .build();
2084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2085 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2086 InputEventInjectionSync::WAIT_FOR_RESULT))
2087 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2088
2089 leftWindow->consumeMotionMove();
2090 // Since the touch is split, right window gets ACTION_DOWN
2091 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00002092 wallpaperWindow->consumeMotionPointerDown(/*pointerIndex=*/1, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002093 expectedWallpaperFlags);
2094
2095 // Now, leftWindow, which received the first finger, disappears.
2096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
2097 leftWindow->consumeMotionCancel();
2098 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
2099 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2100
2101 // The pointer that's still down on the right window moves, and goes to the right window only.
2102 // As far as the dispatcher's concerned though, both pointers are still present.
2103 const MotionEvent secondFingerMoveEvent =
2104 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
2105 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00002106 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2107 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(310).y(110))
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002108 .build();
2109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2110 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
2111 InputEventInjectionSync::WAIT_FOR_RESULT));
2112 rightWindow->consumeMotionMove();
2113
2114 leftWindow->assertNoEvents();
2115 rightWindow->assertNoEvents();
2116 wallpaperWindow->assertNoEvents();
2117}
2118
Arthur Hungc539dbb2022-12-08 07:45:36 +00002119/**
2120 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
2121 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
2122 * The right window should receive ACTION_DOWN.
2123 */
2124TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungc539dbb2022-12-08 07:45:36 +00002126 sp<FakeWindowHandle> leftWindow =
2127 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2128 leftWindow->setFrame(Rect(0, 0, 200, 200));
2129 leftWindow->setDupTouchToWallpaper(true);
2130 leftWindow->setSlippery(true);
2131
2132 sp<FakeWindowHandle> rightWindow =
2133 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2134 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung74c248d2022-11-23 07:09:59 +00002135
2136 sp<FakeWindowHandle> wallpaperWindow =
2137 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2138 wallpaperWindow->setIsWallpaper(true);
Arthur Hung74c248d2022-11-23 07:09:59 +00002139
Arthur Hungc539dbb2022-12-08 07:45:36 +00002140 mDispatcher->setInputWindows(
2141 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung74c248d2022-11-23 07:09:59 +00002142
Arthur Hungc539dbb2022-12-08 07:45:36 +00002143 // Touch down on left window
Arthur Hung74c248d2022-11-23 07:09:59 +00002144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2145 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002146 {100, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungc539dbb2022-12-08 07:45:36 +00002148
2149 // Both foreground window and its wallpaper should receive the touch down
2150 leftWindow->consumeMotionDown();
Arthur Hung74c248d2022-11-23 07:09:59 +00002151 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2152
Arthur Hungc539dbb2022-12-08 07:45:36 +00002153 // Move to right window, the left window should receive cancel.
Arthur Hung74c248d2022-11-23 07:09:59 +00002154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungc539dbb2022-12-08 07:45:36 +00002155 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2156 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung74c248d2022-11-23 07:09:59 +00002157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2158
Arthur Hungc539dbb2022-12-08 07:45:36 +00002159 leftWindow->consumeMotionCancel();
2160 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2161 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung74c248d2022-11-23 07:09:59 +00002162}
2163
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002164/**
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08002165 * The policy typically sets POLICY_FLAG_PASS_TO_USER to the events. But when the display is not
2166 * interactive, it might stop sending this flag.
2167 * In this test, we check that if the policy stops sending this flag mid-gesture, we still ensure
2168 * to have a consistent input stream.
2169 *
2170 * Test procedure:
2171 * DOWN -> POINTER_DOWN -> (stop sending POLICY_FLAG_PASS_TO_USER) -> CANCEL.
2172 * DOWN (new gesture).
2173 *
2174 * In the bad implementation, we could potentially drop the CANCEL event, and get an inconsistent
2175 * state in the dispatcher. This would cause the final DOWN event to not be delivered to the app.
2176 *
2177 * We technically just need a single window here, but we are using two windows (spy on top and a
2178 * regular window below) to emulate the actual situation where it happens on the device.
2179 */
2180TEST_F(InputDispatcherTest, TwoPointerCancelInconsistentPolicy) {
2181 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2182 sp<FakeWindowHandle> spyWindow =
2183 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2184 spyWindow->setFrame(Rect(0, 0, 200, 200));
2185 spyWindow->setTrustedOverlay(true);
2186 spyWindow->setSpy(true);
2187
2188 sp<FakeWindowHandle> window =
2189 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2190 window->setFrame(Rect(0, 0, 200, 200));
2191
2192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2193 const int32_t touchDeviceId = 4;
2194 NotifyMotionArgs args;
2195
2196 // Two pointers down
2197 mDispatcher->notifyMotion(&(
2198 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2199 .deviceId(touchDeviceId)
2200 .policyFlags(DEFAULT_POLICY_FLAGS)
2201 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2202 .build()));
2203
2204 mDispatcher->notifyMotion(&(
2205 args = MotionArgsBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2206 .deviceId(touchDeviceId)
2207 .policyFlags(DEFAULT_POLICY_FLAGS)
2208 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2209 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2210 .build()));
2211 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2212 spyWindow->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2213 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2214 window->consumeMotionEvent(WithMotionAction(POINTER_1_DOWN));
2215
2216 // Cancel the current gesture. Send the cancel without the default policy flags.
2217 mDispatcher->notifyMotion(&(
2218 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_CANCEL, AINPUT_SOURCE_TOUCHSCREEN)
2219 .deviceId(touchDeviceId)
2220 .policyFlags(0)
2221 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2222 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(120).y(120))
2223 .build()));
2224 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2225 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL));
2226
2227 // We don't need to reset the device to reproduce the issue, but the reset event typically
2228 // follows, so we keep it here to model the actual listener behaviour more closely.
2229 NotifyDeviceResetArgs resetArgs;
2230 resetArgs.id = 1; // arbitrary id
2231 resetArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2232 resetArgs.deviceId = touchDeviceId;
2233 mDispatcher->notifyDeviceReset(&resetArgs);
2234
2235 // Start new gesture
2236 mDispatcher->notifyMotion(&(
2237 args = MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2238 .deviceId(touchDeviceId)
2239 .policyFlags(DEFAULT_POLICY_FLAGS)
2240 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(100))
2241 .build()));
2242 spyWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2243 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2244
2245 // No more events
2246 spyWindow->assertNoEvents();
2247 window->assertNoEvents();
2248}
2249
2250/**
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002251 * Two windows: a window on the left and a window on the right.
2252 * Mouse is hovered from the right window into the left window.
2253 * Next, we tap on the left window, where the cursor was last seen.
2254 * The second tap is done onto the right window.
2255 * The mouse and tap are from two different devices.
2256 * We technically don't need to set the downtime / eventtime for these events, but setting these
2257 * explicitly helps during debugging.
2258 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2259 * In the buggy implementation, a tap on the right window would cause a crash.
2260 */
2261TEST_F(InputDispatcherTest, HoverFromLeftToRightAndTap) {
2262 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2263 sp<FakeWindowHandle> leftWindow =
2264 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2265 leftWindow->setFrame(Rect(0, 0, 200, 200));
2266
2267 sp<FakeWindowHandle> rightWindow =
2268 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2269 rightWindow->setFrame(Rect(200, 0, 400, 200));
2270
2271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2272 // All times need to start at the current time, otherwise the dispatcher will drop the events as
2273 // stale.
2274 const nsecs_t baseTime = systemTime(SYSTEM_TIME_MONOTONIC);
2275 const int32_t mouseDeviceId = 6;
2276 const int32_t touchDeviceId = 4;
2277 // Move the cursor from right
2278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2279 injectMotionEvent(mDispatcher,
2280 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2281 AINPUT_SOURCE_MOUSE)
2282 .deviceId(mouseDeviceId)
2283 .downTime(baseTime + 10)
2284 .eventTime(baseTime + 20)
2285 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2286 .x(300)
2287 .y(100))
2288 .build()));
2289 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2290
2291 // .. to the left window
2292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2293 injectMotionEvent(mDispatcher,
2294 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2295 AINPUT_SOURCE_MOUSE)
2296 .deviceId(mouseDeviceId)
2297 .downTime(baseTime + 10)
2298 .eventTime(baseTime + 30)
2299 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2300 .x(110)
2301 .y(100))
2302 .build()));
2303 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2304 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2305 // Now tap the left window
2306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2307 injectMotionEvent(mDispatcher,
2308 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2309 AINPUT_SOURCE_TOUCHSCREEN)
2310 .deviceId(touchDeviceId)
2311 .downTime(baseTime + 40)
2312 .eventTime(baseTime + 40)
2313 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2314 .x(100)
2315 .y(100))
2316 .build()));
2317 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2318 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2319
2320 // release tap
2321 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2322 injectMotionEvent(mDispatcher,
2323 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2324 AINPUT_SOURCE_TOUCHSCREEN)
2325 .deviceId(touchDeviceId)
2326 .downTime(baseTime + 40)
2327 .eventTime(baseTime + 50)
2328 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2329 .x(100)
2330 .y(100))
2331 .build()));
2332 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2333
2334 // Tap the window on the right
2335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2336 injectMotionEvent(mDispatcher,
2337 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2338 AINPUT_SOURCE_TOUCHSCREEN)
2339 .deviceId(touchDeviceId)
2340 .downTime(baseTime + 60)
2341 .eventTime(baseTime + 60)
2342 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2343 .x(300)
2344 .y(100))
2345 .build()));
2346 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2347
2348 // release tap
2349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2350 injectMotionEvent(mDispatcher,
2351 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2352 AINPUT_SOURCE_TOUCHSCREEN)
2353 .deviceId(touchDeviceId)
2354 .downTime(baseTime + 60)
2355 .eventTime(baseTime + 70)
2356 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2357 .x(300)
2358 .y(100))
2359 .build()));
2360 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2361
2362 // No more events
2363 leftWindow->assertNoEvents();
2364 rightWindow->assertNoEvents();
2365}
2366
2367/**
Siarhei Vishniakou6464e462023-02-06 18:57:59 -08002368 * This test is similar to the test above, but the sequence of injected events is different.
2369 *
2370 * Two windows: a window on the left and a window on the right.
2371 * Mouse is hovered over the left window.
2372 * Next, we tap on the left window, where the cursor was last seen.
2373 *
2374 * After that, we inject one finger down onto the right window, and then a second finger down onto
2375 * the left window.
2376 * The touch is split, so this last gesture should cause 2 ACTION_DOWN events, one in the right
2377 * window (first), and then another on the left window (second).
2378 * This test reproduces a crash where there is a mismatch between the downTime and eventTime.
2379 * In the buggy implementation, second finger down on the left window would cause a crash.
2380 */
2381TEST_F(InputDispatcherTest, HoverTapAndSplitTouch) {
2382 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2383 sp<FakeWindowHandle> leftWindow =
2384 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2385 leftWindow->setFrame(Rect(0, 0, 200, 200));
2386
2387 sp<FakeWindowHandle> rightWindow =
2388 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2389 rightWindow->setFrame(Rect(200, 0, 400, 200));
2390
2391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow}}});
2392
2393 const int32_t mouseDeviceId = 6;
2394 const int32_t touchDeviceId = 4;
2395 // Hover over the left window. Keep the cursor there.
2396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2397 injectMotionEvent(mDispatcher,
2398 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2399 AINPUT_SOURCE_MOUSE)
2400 .deviceId(mouseDeviceId)
2401 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2402 .x(50)
2403 .y(50))
2404 .build()));
2405 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2406
2407 // Tap on left window
2408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2409 injectMotionEvent(mDispatcher,
2410 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2411 AINPUT_SOURCE_TOUCHSCREEN)
2412 .deviceId(touchDeviceId)
2413 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2414 .x(100)
2415 .y(100))
2416 .build()));
2417
2418 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2419 injectMotionEvent(mDispatcher,
2420 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2421 AINPUT_SOURCE_TOUCHSCREEN)
2422 .deviceId(touchDeviceId)
2423 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2424 .x(100)
2425 .y(100))
2426 .build()));
2427 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2428 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2429 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2430
2431 // First finger down on right window
2432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2433 injectMotionEvent(mDispatcher,
2434 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2435 AINPUT_SOURCE_TOUCHSCREEN)
2436 .deviceId(touchDeviceId)
2437 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2438 .x(300)
2439 .y(100))
2440 .build()));
2441 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2442
2443 // Second finger down on the left window
2444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2445 injectMotionEvent(mDispatcher,
2446 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2447 .deviceId(touchDeviceId)
2448 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2449 .x(300)
2450 .y(100))
2451 .pointer(PointerBuilder(1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2452 .x(100)
2453 .y(100))
2454 .build()));
2455 leftWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2456 rightWindow->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_MOVE));
2457
2458 // No more events
2459 leftWindow->assertNoEvents();
2460 rightWindow->assertNoEvents();
2461}
2462
2463/**
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08002464 * Start hovering with a stylus device, and then tap with a touch device. Ensure no crash occurs.
2465 * While the touch is down, new hover events from the stylus device should be ignored. After the
2466 * touch is gone, stylus hovering should start working again.
2467 */
2468TEST_F(InputDispatcherTest, StylusHoverAndTouchTap) {
2469 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2470 sp<FakeWindowHandle> window =
2471 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2472 window->setFrame(Rect(0, 0, 200, 200));
2473
2474 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2475
2476 const int32_t stylusDeviceId = 5;
2477 const int32_t touchDeviceId = 4;
2478 // Start hovering with stylus
2479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2480 injectMotionEvent(mDispatcher,
2481 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2482 AINPUT_SOURCE_STYLUS)
2483 .deviceId(stylusDeviceId)
2484 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2485 .x(50)
2486 .y(50))
2487 .build()));
2488 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2489
2490 // Finger down on the window
2491 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2492 injectMotionEvent(mDispatcher,
2493 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2494 AINPUT_SOURCE_TOUCHSCREEN)
2495 .deviceId(touchDeviceId)
2496 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2497 .x(100)
2498 .y(100))
2499 .build()));
2500 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2501 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_DOWN));
2502
2503 // Try to continue hovering with stylus. Since we are already down, injection should fail
2504 ASSERT_EQ(InputEventInjectionResult::FAILED,
2505 injectMotionEvent(mDispatcher,
2506 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2507 AINPUT_SOURCE_STYLUS)
2508 .deviceId(stylusDeviceId)
2509 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2510 .x(50)
2511 .y(50))
2512 .build()));
2513 // No event should be sent. This event should be ignored because a pointer from another device
2514 // is already down.
2515
2516 // Lift up the finger
2517 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2518 injectMotionEvent(mDispatcher,
2519 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2520 AINPUT_SOURCE_TOUCHSCREEN)
2521 .deviceId(touchDeviceId)
2522 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2523 .x(100)
2524 .y(100))
2525 .build()));
2526 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_UP));
2527
2528 // Now that the touch is gone, stylus hovering should start working again
2529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2530 injectMotionEvent(mDispatcher,
2531 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2532 AINPUT_SOURCE_STYLUS)
2533 .deviceId(stylusDeviceId)
2534 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
2535 .x(50)
2536 .y(50))
2537 .build()));
2538 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
2539 // No more events
2540 window->assertNoEvents();
2541}
2542
2543/**
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002544 * On the display, have a single window, and also an area where there's no window.
2545 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
2546 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
2547 */
2548TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
2549 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2550 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002551 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002552
2553 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
2554 NotifyMotionArgs args;
2555
2556 // Touch down on the empty space
2557 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
2558
2559 mDispatcher->waitForIdle();
2560 window->assertNoEvents();
2561
2562 // Now touch down on the window with another pointer
2563 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2564 mDispatcher->waitForIdle();
2565 window->consumeMotionDown();
2566}
2567
2568/**
2569 * Same test as above, but instead of touching the empty space, the first touch goes to
2570 * non-touchable window.
2571 */
2572TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2573 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2574 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002575 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002576 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2577 window1->setTouchable(false);
2578 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002579 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002580 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2581
2582 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2583
2584 NotifyMotionArgs args;
2585 // Touch down on the non-touchable window
2586 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2587
2588 mDispatcher->waitForIdle();
2589 window1->assertNoEvents();
2590 window2->assertNoEvents();
2591
2592 // Now touch down on the window with another pointer
2593 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2594 mDispatcher->waitForIdle();
2595 window2->consumeMotionDown();
2596}
2597
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002598/**
2599 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2600 * to the event time of the first ACTION_DOWN sent to the particular window.
2601 */
2602TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2603 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2604 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002605 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002606 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2607 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002608 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002609 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2610
2611 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2612
2613 NotifyMotionArgs args;
2614 // Touch down on the first window
2615 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2616
2617 mDispatcher->waitForIdle();
2618 InputEvent* inputEvent1 = window1->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002619 ASSERT_NE(inputEvent1, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002620 window2->assertNoEvents();
2621 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2622 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2623 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2624
2625 // Now touch down on the window with another pointer
2626 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2627 mDispatcher->waitForIdle();
2628 InputEvent* inputEvent2 = window2->consume();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002629 ASSERT_NE(inputEvent2, nullptr);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002630 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2631 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2632 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2633 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2634
2635 // Now move the pointer on the second window
2636 mDispatcher->notifyMotion(
2637 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2638 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002639 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002640
2641 // Now add new touch down on the second window
2642 mDispatcher->notifyMotion(
2643 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2644 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002645 window2->consumeMotionEvent(WithDownTime(downTimeForWindow2));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002646
2647 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2648 window1->consumeMotionMove();
2649 window1->assertNoEvents();
2650
2651 // Now move the pointer on the first window
2652 mDispatcher->notifyMotion(
2653 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2654 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002655 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002656
2657 mDispatcher->notifyMotion(&(
2658 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2659 mDispatcher->waitForIdle();
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08002660 window1->consumeMotionEvent(WithDownTime(downTimeForWindow1));
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002661}
2662
Garfield Tandf26e862020-07-01 20:18:19 -07002663TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002664 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002665 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002666 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002667 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002668 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002669 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002670 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002671
2672 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2673
2674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2675
2676 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002678 injectMotionEvent(mDispatcher,
2679 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2680 AINPUT_SOURCE_MOUSE)
2681 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2682 .x(900)
2683 .y(400))
2684 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002685 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002686
2687 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002689 injectMotionEvent(mDispatcher,
2690 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2691 AINPUT_SOURCE_MOUSE)
2692 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2693 .x(300)
2694 .y(400))
2695 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002696 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2697 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002698
2699 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002701 injectMotionEvent(mDispatcher,
2702 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2703 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2704 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2705 .x(300)
2706 .y(400))
2707 .build()));
2708 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2709
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002711 injectMotionEvent(mDispatcher,
2712 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2713 AINPUT_SOURCE_MOUSE)
2714 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2715 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2716 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2717 .x(300)
2718 .y(400))
2719 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002720 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002721
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002723 injectMotionEvent(mDispatcher,
2724 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2725 AINPUT_SOURCE_MOUSE)
2726 .buttonState(0)
2727 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2728 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2729 .x(300)
2730 .y(400))
2731 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002732 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002733
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002735 injectMotionEvent(mDispatcher,
2736 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2737 .buttonState(0)
2738 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2739 .x(300)
2740 .y(400))
2741 .build()));
2742 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2743
2744 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002746 injectMotionEvent(mDispatcher,
2747 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2748 AINPUT_SOURCE_MOUSE)
2749 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2750 .x(900)
2751 .y(400))
2752 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002753 windowLeft->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
2754 windowRight->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002755
2756 // No more events
2757 windowLeft->assertNoEvents();
2758 windowRight->assertNoEvents();
2759}
2760
2761TEST_F(InputDispatcherTest, HoverWithSpyWindows) {
2762 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2763
2764 sp<FakeWindowHandle> spyWindow =
2765 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2766 spyWindow->setFrame(Rect(0, 0, 600, 800));
2767 spyWindow->setTrustedOverlay(true);
2768 spyWindow->setSpy(true);
2769 sp<FakeWindowHandle> window =
2770 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2771 window->setFrame(Rect(0, 0, 600, 800));
2772
2773 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2775
2776 // Send mouse cursor to the window
2777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2778 injectMotionEvent(mDispatcher,
2779 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2780 AINPUT_SOURCE_MOUSE)
2781 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2782 .x(100)
2783 .y(100))
2784 .build()));
2785
2786 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2787 WithSource(AINPUT_SOURCE_MOUSE)));
2788 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2789 WithSource(AINPUT_SOURCE_MOUSE)));
2790
2791 window->assertNoEvents();
2792 spyWindow->assertNoEvents();
Garfield Tandf26e862020-07-01 20:18:19 -07002793}
2794
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002795TEST_F(InputDispatcherTest, MouseAndTouchWithSpyWindows) {
2796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2797
2798 sp<FakeWindowHandle> spyWindow =
2799 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2800 spyWindow->setFrame(Rect(0, 0, 600, 800));
2801 spyWindow->setTrustedOverlay(true);
2802 spyWindow->setSpy(true);
2803 sp<FakeWindowHandle> window =
2804 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2805 window->setFrame(Rect(0, 0, 600, 800));
2806
2807 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, window}}});
2809
2810 // Send mouse cursor to the window
2811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2812 injectMotionEvent(mDispatcher,
2813 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2814 AINPUT_SOURCE_MOUSE)
2815 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2816 .x(100)
2817 .y(100))
2818 .build()));
2819
2820 // Move mouse cursor
2821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2822 injectMotionEvent(mDispatcher,
2823 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2824 AINPUT_SOURCE_MOUSE)
2825 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2826 .x(110)
2827 .y(110))
2828 .build()));
2829
2830 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2831 WithSource(AINPUT_SOURCE_MOUSE)));
2832 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2833 WithSource(AINPUT_SOURCE_MOUSE)));
2834 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2835 WithSource(AINPUT_SOURCE_MOUSE)));
2836 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2837 WithSource(AINPUT_SOURCE_MOUSE)));
2838 // Touch down on the window
2839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2840 injectMotionEvent(mDispatcher,
2841 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2842 AINPUT_SOURCE_TOUCHSCREEN)
2843 .deviceId(SECOND_DEVICE_ID)
2844 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2845 .x(200)
2846 .y(200))
2847 .build()));
2848 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2849 WithSource(AINPUT_SOURCE_MOUSE)));
2850 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2851 WithSource(AINPUT_SOURCE_MOUSE)));
2852 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2853 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2854 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2855 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2856
2857 // pilfer the motion, retaining the gesture on the spy window.
2858 EXPECT_EQ(OK, mDispatcher->pilferPointers(spyWindow->getToken()));
2859 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
2860 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2861
2862 // Touch UP on the window
2863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2864 injectMotionEvent(mDispatcher,
2865 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2866 AINPUT_SOURCE_TOUCHSCREEN)
2867 .deviceId(SECOND_DEVICE_ID)
2868 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2869 .x(200)
2870 .y(200))
2871 .build()));
2872 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2873 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2874
2875 // Previously, a touch was pilfered. However, that gesture was just finished. Now, we are going
2876 // to send a new gesture. It should again go to both windows (spy and the window below), just
2877 // like the first gesture did, before pilfering. The window configuration has not changed.
2878
2879 // One more tap - DOWN
2880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2881 injectMotionEvent(mDispatcher,
2882 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
2883 AINPUT_SOURCE_TOUCHSCREEN)
2884 .deviceId(SECOND_DEVICE_ID)
2885 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2886 .x(250)
2887 .y(250))
2888 .build()));
2889 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2890 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2891 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2892 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2893
2894 // Touch UP on the window
2895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2896 injectMotionEvent(mDispatcher,
2897 MotionEventBuilder(AMOTION_EVENT_ACTION_UP,
2898 AINPUT_SOURCE_TOUCHSCREEN)
2899 .deviceId(SECOND_DEVICE_ID)
2900 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2901 .x(250)
2902 .y(250))
2903 .build()));
2904 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2905 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2906 spyWindow->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2907 WithSource(AINPUT_SOURCE_TOUCHSCREEN)));
2908
2909 window->assertNoEvents();
2910 spyWindow->assertNoEvents();
2911}
2912
Garfield Tandf26e862020-07-01 20:18:19 -07002913// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2914// directly in this test.
2915TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002917 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002918 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002919 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002920
2921 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2922
2923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002926 injectMotionEvent(mDispatcher,
2927 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2928 AINPUT_SOURCE_MOUSE)
2929 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2930 .x(300)
2931 .y(400))
2932 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002933 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Garfield Tandf26e862020-07-01 20:18:19 -07002934 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002936 injectMotionEvent(mDispatcher,
2937 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2938 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2939 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2940 .x(300)
2941 .y(400))
2942 .build()));
2943 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002946 injectMotionEvent(mDispatcher,
2947 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2948 AINPUT_SOURCE_MOUSE)
2949 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2950 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2951 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2952 .x(300)
2953 .y(400))
2954 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002955 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS));
Garfield Tandf26e862020-07-01 20:18:19 -07002956
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002958 injectMotionEvent(mDispatcher,
2959 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2960 AINPUT_SOURCE_MOUSE)
2961 .buttonState(0)
2962 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2963 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2964 .x(300)
2965 .y(400))
2966 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002967 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE));
Garfield Tandf26e862020-07-01 20:18:19 -07002968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002970 injectMotionEvent(mDispatcher,
2971 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2972 .buttonState(0)
2973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2974 .x(300)
2975 .y(400))
2976 .build()));
2977 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002980 injectMotionEvent(mDispatcher,
2981 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2982 AINPUT_SOURCE_MOUSE)
2983 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2984 .x(300)
2985 .y(400))
2986 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002987 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
Garfield Tandf26e862020-07-01 20:18:19 -07002988}
2989
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002990/**
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002991 * Hover over a window, and then remove that window. Make sure that HOVER_EXIT for that event
2992 * is generated.
2993 */
2994TEST_F(InputDispatcherTest, HoverExitIsSentToRemovedWindow) {
2995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2996 sp<FakeWindowHandle> window =
2997 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2998 window->setFrame(Rect(0, 0, 1200, 800));
2999
3000 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3001
3002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3003
3004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3005 injectMotionEvent(mDispatcher,
3006 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
3007 AINPUT_SOURCE_MOUSE)
3008 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3009 .x(300)
3010 .y(400))
3011 .build()));
3012 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
3013
3014 // Remove the window, but keep the channel.
3015 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3016 window->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT));
3017}
3018
3019/**
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003020 * Inject a mouse hover event followed by a tap from touchscreen.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003021 * The tap causes a HOVER_EXIT event to be generated because the current event
3022 * stream's source has been switched.
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003023 */
3024TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
3025 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3026 sp<FakeWindowHandle> window =
3027 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3028 window->setFrame(Rect(0, 0, 100, 100));
3029
3030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3031
3032 // Inject a hover_move from mouse.
3033 NotifyMotionArgs motionArgs =
3034 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
3035 ADISPLAY_ID_DEFAULT, {{50, 50}});
3036 motionArgs.xCursorPosition = 50;
3037 motionArgs.yCursorPosition = 50;
3038 mDispatcher->notifyMotion(&motionArgs);
3039 ASSERT_NO_FATAL_FAILURE(
3040 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
3041 WithSource(AINPUT_SOURCE_MOUSE))));
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003042
3043 // Tap on the window
3044 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3045 ADISPLAY_ID_DEFAULT, {{10, 10}});
3046 mDispatcher->notifyMotion(&motionArgs);
3047 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00003048 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
3049 WithSource(AINPUT_SOURCE_MOUSE))));
3050
3051 ASSERT_NO_FATAL_FAILURE(
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08003052 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
3053 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3054
3055 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3056 ADISPLAY_ID_DEFAULT, {{10, 10}});
3057 mDispatcher->notifyMotion(&motionArgs);
3058 ASSERT_NO_FATAL_FAILURE(
3059 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
3060 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
3061}
3062
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003063TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
3064 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3065 sp<FakeWindowHandle> windowDefaultDisplay =
3066 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
3067 ADISPLAY_ID_DEFAULT);
3068 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
3069 sp<FakeWindowHandle> windowSecondDisplay =
3070 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
3071 SECOND_DISPLAY_ID);
3072 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
3073
3074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3075 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3076
3077 // Set cursor position in window in default display and check that hover enter and move
3078 // events are generated.
3079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3080 injectMotionEvent(mDispatcher,
3081 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3082 AINPUT_SOURCE_MOUSE)
3083 .displayId(ADISPLAY_ID_DEFAULT)
3084 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3085 .x(300)
3086 .y(600))
3087 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003088 windowDefaultDisplay->consumeMotionEvent(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003089
3090 // Remove all windows in secondary display and check that no event happens on window in
3091 // primary display.
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003092 mDispatcher->setInputWindows(
3093 {{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}}, {SECOND_DISPLAY_ID, {}}});
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003094 windowDefaultDisplay->assertNoEvents();
3095
3096 // Move cursor position in window in default display and check that only hover move
3097 // event is generated and not hover enter event.
3098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
3099 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
3100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3101 injectMotionEvent(mDispatcher,
3102 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
3103 AINPUT_SOURCE_MOUSE)
3104 .displayId(ADISPLAY_ID_DEFAULT)
3105 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
3106 .x(400)
3107 .y(700))
3108 .build()));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003109 windowDefaultDisplay->consumeMotionEvent(
3110 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
3111 WithSource(AINPUT_SOURCE_MOUSE)));
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02003112 windowDefaultDisplay->assertNoEvents();
3113}
3114
Garfield Tan00f511d2019-06-12 16:55:40 -07003115TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07003116 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07003117
3118 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003119 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003120 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003121 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003122 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003123 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07003124
3125 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3126
Arthur Hung72d8dc32020-03-28 00:48:39 +00003127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07003128
3129 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
3130 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07003132 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003133 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003134 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07003135 windowRight->assertNoEvents();
3136}
3137
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003138TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003139 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003140 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3141 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07003142 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003143
Arthur Hung72d8dc32020-03-28 00:48:39 +00003144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003145 setFocusedWindow(window);
3146
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003147 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003148
3149 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3150 mDispatcher->notifyKey(&keyArgs);
3151
3152 // Window should receive key down event.
3153 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3154
3155 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
3156 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003157 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003158 mDispatcher->notifyDeviceReset(&args);
3159 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3160 AKEY_EVENT_FLAG_CANCELED);
3161}
3162
3163TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07003164 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003165 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3166 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003167
Arthur Hung72d8dc32020-03-28 00:48:39 +00003168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003169
3170 NotifyMotionArgs motionArgs =
3171 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3172 ADISPLAY_ID_DEFAULT);
3173 mDispatcher->notifyMotion(&motionArgs);
3174
3175 // Window should receive motion down event.
3176 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3177
3178 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
3179 // on the app side.
Harry Cutts33476232023-01-30 19:57:29 +00003180 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003181 mDispatcher->notifyDeviceReset(&args);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003182 window->consumeMotionEvent(
3183 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003184}
3185
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003186TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
3187 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003188 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3189 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003190 window->setFocusable(true);
3191
3192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3193 setFocusedWindow(window);
3194
3195 window->consumeFocusEvent(true);
3196
3197 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3198 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
3199 const nsecs_t injectTime = keyArgs.eventTime;
3200 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
3201 mDispatcher->notifyKey(&keyArgs);
3202 // The dispatching time should be always greater than or equal to intercept key timeout.
3203 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3204 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
3205 std::chrono::nanoseconds(interceptKeyTimeout).count());
3206}
3207
3208TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
3209 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003210 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3211 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08003212 window->setFocusable(true);
3213
3214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3215 setFocusedWindow(window);
3216
3217 window->consumeFocusEvent(true);
3218
3219 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3220 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3221 mFakePolicy->setInterceptKeyTimeout(150ms);
3222 mDispatcher->notifyKey(&keyDown);
3223 mDispatcher->notifyKey(&keyUp);
3224
3225 // Window should receive key event immediately when same key up.
3226 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3227 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3228}
3229
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003230/**
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003231 * Two windows. First is a regular window. Second does not overlap with the first, and has
3232 * WATCH_OUTSIDE_TOUCH.
3233 * Both windows are owned by the same UID.
3234 * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
3235 * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
3236 */
3237TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
3238 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3239 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3240 "First Window", ADISPLAY_ID_DEFAULT);
3241 window->setFrame(Rect{0, 0, 100, 100});
3242
3243 sp<FakeWindowHandle> outsideWindow =
3244 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3245 ADISPLAY_ID_DEFAULT);
3246 outsideWindow->setFrame(Rect{100, 100, 200, 200});
3247 outsideWindow->setWatchOutsideTouch(true);
3248 // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
3249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
3250
3251 // Tap on first window.
3252 NotifyMotionArgs motionArgs =
3253 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3254 ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
3255 mDispatcher->notifyMotion(&motionArgs);
3256 window->consumeMotionDown();
3257 // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
3258 // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
3259 outsideWindow->consumeMotionEvent(
3260 AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
3261}
3262
3263/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003264 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
3265 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
3266 * ACTION_OUTSIDE event is sent per gesture.
3267 */
3268TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
3269 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
3270 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003271 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3272 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003273 window->setWatchOutsideTouch(true);
3274 window->setFrame(Rect{0, 0, 100, 100});
3275 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003276 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3277 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003278 secondWindow->setFrame(Rect{100, 100, 200, 200});
3279 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003280 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
3281 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003282 thirdWindow->setFrame(Rect{200, 200, 300, 300});
3283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
3284
3285 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
3286 NotifyMotionArgs motionArgs =
3287 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3288 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
3289 mDispatcher->notifyMotion(&motionArgs);
3290 window->assertNoEvents();
3291 secondWindow->assertNoEvents();
3292
3293 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
3294 // Now, `window` should get ACTION_OUTSIDE.
3295 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3296 {PointF{-10, -10}, PointF{105, 105}});
3297 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou487c49b2022-12-02 15:48:57 -08003298 const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
3299 window->consumeMotionEvent(
3300 AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003301 secondWindow->consumeMotionDown();
3302 thirdWindow->assertNoEvents();
3303
3304 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
3305 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
3306 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3307 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
3308 mDispatcher->notifyMotion(&motionArgs);
3309 window->assertNoEvents();
3310 secondWindow->consumeMotionMove();
3311 thirdWindow->consumeMotionDown();
3312}
3313
Prabir Pradhan814fe082022-07-22 20:22:18 +00003314TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
3315 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003316 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3317 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00003318 window->setFocusable(true);
3319
3320 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3321 setFocusedWindow(window);
3322
3323 window->consumeFocusEvent(true);
3324
3325 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3326 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3327 mDispatcher->notifyKey(&keyDown);
3328 mDispatcher->notifyKey(&keyUp);
3329
3330 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3331 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
3332
3333 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
3334 mDispatcher->onWindowInfosChanged({}, {});
3335
3336 window->consumeFocusEvent(false);
3337
3338 mDispatcher->notifyKey(&keyDown);
3339 mDispatcher->notifyKey(&keyUp);
3340 window->assertNoEvents();
3341}
3342
Arthur Hung96483742022-11-15 03:30:48 +00003343TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
3344 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3345 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3346 "Fake Window", ADISPLAY_ID_DEFAULT);
3347 // Ensure window is non-split and have some transform.
3348 window->setPreventSplitting(true);
3349 window->setWindowOffset(20, 40);
3350 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
3351
3352 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3353 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3354 {50, 50}))
3355 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3356 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3357
3358 const MotionEvent secondFingerDownEvent =
3359 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3360 .displayId(ADISPLAY_ID_DEFAULT)
3361 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003362 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3363 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-30).y(-50))
Arthur Hung96483742022-11-15 03:30:48 +00003364 .build();
3365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3366 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3367 InputEventInjectionSync::WAIT_FOR_RESULT))
3368 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3369
3370 const MotionEvent* event = window->consumeMotion();
3371 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
3372 EXPECT_EQ(70, event->getX(0)); // 50 + 20
3373 EXPECT_EQ(90, event->getY(0)); // 50 + 40
3374 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
3375 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
3376}
3377
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00003378/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003379 * Ensure the correct coordinate spaces are used by InputDispatcher.
3380 *
3381 * InputDispatcher works in the display space, so its coordinate system is relative to the display
3382 * panel. Windows get events in the window space, and get raw coordinates in the logical display
3383 * space.
3384 */
3385class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
3386public:
3387 void SetUp() override {
3388 InputDispatcherTest::SetUp();
3389 mDisplayInfos.clear();
3390 mWindowInfos.clear();
3391 }
3392
3393 void addDisplayInfo(int displayId, const ui::Transform& transform) {
3394 gui::DisplayInfo info;
3395 info.displayId = displayId;
3396 info.transform = transform;
3397 mDisplayInfos.push_back(std::move(info));
3398 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3399 }
3400
3401 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
3402 mWindowInfos.push_back(*windowHandle->getInfo());
3403 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
3404 }
3405
3406 // Set up a test scenario where the display has a scaled projection and there are two windows
3407 // on the display.
3408 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
3409 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
3410 // respectively.
3411 ui::Transform displayTransform;
3412 displayTransform.set(2, 0, 0, 4);
3413 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
3414
3415 std::shared_ptr<FakeApplicationHandle> application =
3416 std::make_shared<FakeApplicationHandle>();
3417
3418 // Add two windows to the display. Their frames are represented in the display space.
3419 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003420 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3421 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003422 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
3423 addWindow(firstWindow);
3424
3425 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003426 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3427 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003428 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
3429 addWindow(secondWindow);
3430 return {std::move(firstWindow), std::move(secondWindow)};
3431 }
3432
3433private:
3434 std::vector<gui::DisplayInfo> mDisplayInfos;
3435 std::vector<gui::WindowInfo> mWindowInfos;
3436};
3437
3438TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
3439 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3440 // Send down to the first window. The point is represented in the display space. The point is
3441 // selected so that if the hit test was done with the transform applied to it, then it would
3442 // end up in the incorrect window.
3443 NotifyMotionArgs downMotionArgs =
3444 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3445 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
3446 mDispatcher->notifyMotion(&downMotionArgs);
3447
3448 firstWindow->consumeMotionDown();
3449 secondWindow->assertNoEvents();
3450}
3451
3452// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
3453// the event should be treated as being in the logical display space.
3454TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
3455 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3456 // Send down to the first window. The point is represented in the logical display space. The
3457 // point is selected so that if the hit test was done in logical display space, then it would
3458 // end up in the incorrect window.
3459 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3460 PointF{75 * 2, 55 * 4});
3461
3462 firstWindow->consumeMotionDown();
3463 secondWindow->assertNoEvents();
3464}
3465
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003466// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
3467// event should be treated as being in the logical display space.
3468TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
3469 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3470
3471 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
3472 ui::Transform injectedEventTransform;
3473 injectedEventTransform.set(matrix);
3474 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
3475 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
3476
3477 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
3478 .displayId(ADISPLAY_ID_DEFAULT)
3479 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00003480 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER)
Prabir Pradhandaa2f142021-12-10 09:30:08 +00003481 .x(untransformedPoint.x)
3482 .y(untransformedPoint.y))
3483 .build();
3484 event.transform(matrix);
3485
3486 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
3487 InputEventInjectionSync::WAIT_FOR_RESULT);
3488
3489 firstWindow->consumeMotionDown();
3490 secondWindow->assertNoEvents();
3491}
3492
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07003493TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
3494 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
3495
3496 // Send down to the second window.
3497 NotifyMotionArgs downMotionArgs =
3498 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3499 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
3500 mDispatcher->notifyMotion(&downMotionArgs);
3501
3502 firstWindow->assertNoEvents();
3503 const MotionEvent* event = secondWindow->consumeMotion();
3504 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
3505
3506 // Ensure that the events from the "getRaw" API are in logical display coordinates.
3507 EXPECT_EQ(300, event->getRawX(0));
3508 EXPECT_EQ(880, event->getRawY(0));
3509
3510 // Ensure that the x and y values are in the window's coordinate space.
3511 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
3512 // the logical display space. This will be the origin of the window space.
3513 EXPECT_EQ(100, event->getX(0));
3514 EXPECT_EQ(80, event->getY(0));
3515}
3516
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003517using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
3518 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003519
3520class TransferTouchFixture : public InputDispatcherTest,
3521 public ::testing::WithParamInterface<TransferFunction> {};
3522
3523TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07003524 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003525
3526 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003527 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003528 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3529 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003530 firstWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003531 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003532 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3533 ADISPLAY_ID_DEFAULT);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003534 sp<FakeWindowHandle> wallpaper =
3535 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
3536 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003537 // Add the windows to the dispatcher
Arthur Hungc539dbb2022-12-08 07:45:36 +00003538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003539
3540 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003541 NotifyMotionArgs downMotionArgs =
3542 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3543 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003544 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungc539dbb2022-12-08 07:45:36 +00003545
Svet Ganov5d3bc372020-01-26 23:11:07 -08003546 // Only the first window should get the down event
3547 firstWindow->consumeMotionDown();
3548 secondWindow->assertNoEvents();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003549 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003550
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003551 // Transfer touch to the second window
3552 TransferFunction f = GetParam();
3553 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3554 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003555 // The first window gets cancel and the second gets down
3556 firstWindow->consumeMotionCancel();
3557 secondWindow->consumeMotionDown();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003558 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003559
3560 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003561 NotifyMotionArgs upMotionArgs =
3562 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3563 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003564 mDispatcher->notifyMotion(&upMotionArgs);
3565 // The first window gets no events and the second gets up
3566 firstWindow->assertNoEvents();
3567 secondWindow->consumeMotionUp();
Arthur Hungc539dbb2022-12-08 07:45:36 +00003568 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569}
3570
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003571/**
3572 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
3573 * from. When we have spy windows, there are several windows to choose from: either spy, or the
3574 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
3575 * natural to the user.
3576 * In this test, we are sending a pointer to both spy window and first window. We then try to
3577 * transfer touch to the second window. The dispatcher should identify the first window as the
3578 * one that should lose the gesture, and therefore the action should be to move the gesture from
3579 * the first window to the second.
3580 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
3581 * the other API, as well.
3582 */
3583TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
3584 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3585
3586 // Create a couple of windows + a spy window
3587 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003588 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003589 spyWindow->setTrustedOverlay(true);
3590 spyWindow->setSpy(true);
3591 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003592 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003593 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003594 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003595
3596 // Add the windows to the dispatcher
3597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
3598
3599 // Send down to the first window
3600 NotifyMotionArgs downMotionArgs =
3601 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3602 ADISPLAY_ID_DEFAULT);
3603 mDispatcher->notifyMotion(&downMotionArgs);
3604 // Only the first window and spy should get the down event
3605 spyWindow->consumeMotionDown();
3606 firstWindow->consumeMotionDown();
3607
3608 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
3609 // if f === 'transferTouch'.
3610 TransferFunction f = GetParam();
3611 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3612 ASSERT_TRUE(success);
3613 // The first window gets cancel and the second gets down
3614 firstWindow->consumeMotionCancel();
3615 secondWindow->consumeMotionDown();
3616
3617 // Send up event to the second window
3618 NotifyMotionArgs upMotionArgs =
3619 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3620 ADISPLAY_ID_DEFAULT);
3621 mDispatcher->notifyMotion(&upMotionArgs);
3622 // The first window gets no events and the second+spy get up
3623 firstWindow->assertNoEvents();
3624 spyWindow->consumeMotionUp();
3625 secondWindow->consumeMotionUp();
3626}
3627
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003628TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003630
3631 PointF touchPoint = {10, 10};
3632
3633 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003634 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003635 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3636 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003637 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003638 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003639 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3640 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003641 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003642
3643 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003645
3646 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003647 NotifyMotionArgs downMotionArgs =
3648 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3649 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003650 mDispatcher->notifyMotion(&downMotionArgs);
3651 // Only the first window should get the down event
3652 firstWindow->consumeMotionDown();
3653 secondWindow->assertNoEvents();
3654
3655 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003656 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003657 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003658 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659 mDispatcher->notifyMotion(&pointerDownMotionArgs);
3660 // Only the first window should get the pointer down event
3661 firstWindow->consumeMotionPointerDown(1);
3662 secondWindow->assertNoEvents();
3663
3664 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003665 TransferFunction f = GetParam();
3666 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3667 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003668 // The first window gets cancel and the second gets down and pointer down
3669 firstWindow->consumeMotionCancel();
3670 secondWindow->consumeMotionDown();
3671 secondWindow->consumeMotionPointerDown(1);
3672
3673 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003674 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003675 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003676 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003677 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3678 // The first window gets nothing and the second gets pointer up
3679 firstWindow->assertNoEvents();
3680 secondWindow->consumeMotionPointerUp(1);
3681
3682 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003683 NotifyMotionArgs upMotionArgs =
3684 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3685 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003686 mDispatcher->notifyMotion(&upMotionArgs);
3687 // The first window gets nothing and the second gets up
3688 firstWindow->assertNoEvents();
3689 secondWindow->consumeMotionUp();
3690}
3691
Arthur Hungc539dbb2022-12-08 07:45:36 +00003692TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
3693 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3694
3695 // Create a couple of windows
3696 sp<FakeWindowHandle> firstWindow =
3697 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3698 ADISPLAY_ID_DEFAULT);
3699 firstWindow->setDupTouchToWallpaper(true);
3700 sp<FakeWindowHandle> secondWindow =
3701 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3702 ADISPLAY_ID_DEFAULT);
3703 secondWindow->setDupTouchToWallpaper(true);
3704
3705 sp<FakeWindowHandle> wallpaper1 =
3706 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
3707 wallpaper1->setIsWallpaper(true);
3708
3709 sp<FakeWindowHandle> wallpaper2 =
3710 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
3711 wallpaper2->setIsWallpaper(true);
3712 // Add the windows to the dispatcher
3713 mDispatcher->setInputWindows(
3714 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
3715
3716 // Send down to the first window
3717 NotifyMotionArgs downMotionArgs =
3718 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3719 ADISPLAY_ID_DEFAULT);
3720 mDispatcher->notifyMotion(&downMotionArgs);
3721
3722 // Only the first window should get the down event
3723 firstWindow->consumeMotionDown();
3724 secondWindow->assertNoEvents();
3725 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3726 wallpaper2->assertNoEvents();
3727
3728 // Transfer touch focus to the second window
3729 TransferFunction f = GetParam();
3730 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
3731 ASSERT_TRUE(success);
3732
3733 // The first window gets cancel and the second gets down
3734 firstWindow->consumeMotionCancel();
3735 secondWindow->consumeMotionDown();
3736 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3737 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3738
3739 // Send up event to the second window
3740 NotifyMotionArgs upMotionArgs =
3741 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3742 ADISPLAY_ID_DEFAULT);
3743 mDispatcher->notifyMotion(&upMotionArgs);
3744 // The first window gets no events and the second gets up
3745 firstWindow->assertNoEvents();
3746 secondWindow->consumeMotionUp();
3747 wallpaper1->assertNoEvents();
3748 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
3749}
3750
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003751// For the cases of single pointer touch and two pointers non-split touch, the api's
3752// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
3753// for the case where there are multiple pointers split across several windows.
3754INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
3755 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003756 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3757 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003758 return dispatcher->transferTouch(destChannelToken,
3759 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003760 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003761 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
3762 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003763 return dispatcher->transferTouchFocus(from, to,
Harry Cutts33476232023-01-30 19:57:29 +00003764 /*isDragAndDrop=*/false);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003765 }));
3766
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07003768 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08003769
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003770 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003771 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3772 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003773 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003775 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003776 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3777 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003778 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08003779
3780 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00003781 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003782
3783 PointF pointInFirst = {300, 200};
3784 PointF pointInSecond = {300, 600};
3785
3786 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003787 NotifyMotionArgs firstDownMotionArgs =
3788 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3789 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003790 mDispatcher->notifyMotion(&firstDownMotionArgs);
3791 // Only the first window should get the down event
3792 firstWindow->consumeMotionDown();
3793 secondWindow->assertNoEvents();
3794
3795 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003796 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003797 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003798 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003799 mDispatcher->notifyMotion(&secondDownMotionArgs);
3800 // The first window gets a move and the second a down
3801 firstWindow->consumeMotionMove();
3802 secondWindow->consumeMotionDown();
3803
3804 // Transfer touch focus to the second window
3805 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
3806 // The first window gets cancel and the new gets pointer down (it already saw down)
3807 firstWindow->consumeMotionCancel();
3808 secondWindow->consumeMotionPointerDown(1);
3809
3810 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003811 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003812 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003813 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08003814 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3815 // The first window gets nothing and the second gets pointer up
3816 firstWindow->assertNoEvents();
3817 secondWindow->consumeMotionPointerUp(1);
3818
3819 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003820 NotifyMotionArgs upMotionArgs =
3821 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3822 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003823 mDispatcher->notifyMotion(&upMotionArgs);
3824 // The first window gets nothing and the second gets up
3825 firstWindow->assertNoEvents();
3826 secondWindow->consumeMotionUp();
3827}
3828
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003829// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3830// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3831// touch is not supported, so the touch should continue on those windows and the transferred-to
3832// window should get nothing.
3833TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3834 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3835
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003836 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003837 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3838 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003839 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003840
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003841 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003842 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3843 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003844 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003845
3846 // Add the windows to the dispatcher
3847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3848
3849 PointF pointInFirst = {300, 200};
3850 PointF pointInSecond = {300, 600};
3851
3852 // Send down to the first window
3853 NotifyMotionArgs firstDownMotionArgs =
3854 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3855 ADISPLAY_ID_DEFAULT, {pointInFirst});
3856 mDispatcher->notifyMotion(&firstDownMotionArgs);
3857 // Only the first window should get the down event
3858 firstWindow->consumeMotionDown();
3859 secondWindow->assertNoEvents();
3860
3861 // Send down to the second window
3862 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003863 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003864 {pointInFirst, pointInSecond});
3865 mDispatcher->notifyMotion(&secondDownMotionArgs);
3866 // The first window gets a move and the second a down
3867 firstWindow->consumeMotionMove();
3868 secondWindow->consumeMotionDown();
3869
3870 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003871 const bool transferred =
3872 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003873 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3874 ASSERT_FALSE(transferred);
3875 firstWindow->assertNoEvents();
3876 secondWindow->assertNoEvents();
3877
3878 // The rest of the dispatch should proceed as normal
3879 // Send pointer up to the second window
3880 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003881 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003882 {pointInFirst, pointInSecond});
3883 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3884 // The first window gets MOVE and the second gets pointer up
3885 firstWindow->consumeMotionMove();
3886 secondWindow->consumeMotionUp();
3887
3888 // Send up event to the first window
3889 NotifyMotionArgs upMotionArgs =
3890 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3891 ADISPLAY_ID_DEFAULT);
3892 mDispatcher->notifyMotion(&upMotionArgs);
3893 // The first window gets nothing and the second gets up
3894 firstWindow->consumeMotionUp();
3895 secondWindow->assertNoEvents();
3896}
3897
Arthur Hungabbb9d82021-09-01 14:52:30 +00003898// This case will create two windows and one mirrored window on the default display and mirror
3899// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3900// the windows info of second display before default display.
3901TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3902 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3903 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003904 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003905 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003906 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003907 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003908 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003909
3910 sp<FakeWindowHandle> mirrorWindowInPrimary =
3911 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3912 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003913
3914 sp<FakeWindowHandle> firstWindowInSecondary =
3915 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3916 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003917
3918 sp<FakeWindowHandle> secondWindowInSecondary =
3919 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3920 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003921
3922 // Update window info, let it find window handle of second display first.
3923 mDispatcher->setInputWindows(
3924 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3925 {ADISPLAY_ID_DEFAULT,
3926 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3927
3928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3929 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3930 {50, 50}))
3931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3932
3933 // Window should receive motion event.
3934 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3935
3936 // Transfer touch focus
3937 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3938 secondWindowInPrimary->getToken()));
3939 // The first window gets cancel.
3940 firstWindowInPrimary->consumeMotionCancel();
3941 secondWindowInPrimary->consumeMotionDown();
3942
3943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3944 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3945 ADISPLAY_ID_DEFAULT, {150, 50}))
3946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3947 firstWindowInPrimary->assertNoEvents();
3948 secondWindowInPrimary->consumeMotionMove();
3949
3950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3951 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3952 {150, 50}))
3953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3954 firstWindowInPrimary->assertNoEvents();
3955 secondWindowInPrimary->consumeMotionUp();
3956}
3957
3958// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3959// 'transferTouch' api.
3960TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3961 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3962 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003963 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003964 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003965 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003966 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003967 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003968
3969 sp<FakeWindowHandle> mirrorWindowInPrimary =
3970 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3971 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003972
3973 sp<FakeWindowHandle> firstWindowInSecondary =
3974 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3975 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003976
3977 sp<FakeWindowHandle> secondWindowInSecondary =
3978 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3979 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003980
3981 // Update window info, let it find window handle of second display first.
3982 mDispatcher->setInputWindows(
3983 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3984 {ADISPLAY_ID_DEFAULT,
3985 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3986
3987 // Touch on second display.
3988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3989 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3990 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3991
3992 // Window should receive motion event.
3993 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3994
3995 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003996 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003997
3998 // The first window gets cancel.
3999 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
4000 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
4001
4002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4003 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4004 SECOND_DISPLAY_ID, {150, 50}))
4005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4006 firstWindowInPrimary->assertNoEvents();
4007 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
4008
4009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4010 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
4011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4012 firstWindowInPrimary->assertNoEvents();
4013 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
4014}
4015
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004016TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004017 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004018 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4019 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004020
Vishnu Nair47074b82020-08-14 11:54:47 -07004021 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004023 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004024
4025 window->consumeFocusEvent(true);
4026
4027 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4028 mDispatcher->notifyKey(&keyArgs);
4029
4030 // Window should receive key down event.
4031 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4032}
4033
4034TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004036 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4037 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004038
Arthur Hung72d8dc32020-03-28 00:48:39 +00004039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004040
4041 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4042 mDispatcher->notifyKey(&keyArgs);
4043 mDispatcher->waitForIdle();
4044
4045 window->assertNoEvents();
4046}
4047
4048// If a window is touchable, but does not have focus, it should receive motion events, but not keys
4049TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07004050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004051 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4052 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004053
Arthur Hung72d8dc32020-03-28 00:48:39 +00004054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004055
4056 // Send key
4057 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
4058 mDispatcher->notifyKey(&keyArgs);
4059 // Send motion
4060 NotifyMotionArgs motionArgs =
4061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4062 ADISPLAY_ID_DEFAULT);
4063 mDispatcher->notifyMotion(&motionArgs);
4064
4065 // Window should receive only the motion event
4066 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4067 window->assertNoEvents(); // Key event or focus event will not be received
4068}
4069
arthurhungea3f4fc2020-12-21 23:18:53 +08004070TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
4071 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4072
arthurhungea3f4fc2020-12-21 23:18:53 +08004073 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004074 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
4075 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004076 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08004077
arthurhungea3f4fc2020-12-21 23:18:53 +08004078 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004079 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
4080 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08004081 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08004082
4083 // Add the windows to the dispatcher
4084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
4085
4086 PointF pointInFirst = {300, 200};
4087 PointF pointInSecond = {300, 600};
4088
4089 // Send down to the first window
4090 NotifyMotionArgs firstDownMotionArgs =
4091 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4092 ADISPLAY_ID_DEFAULT, {pointInFirst});
4093 mDispatcher->notifyMotion(&firstDownMotionArgs);
4094 // Only the first window should get the down event
4095 firstWindow->consumeMotionDown();
4096 secondWindow->assertNoEvents();
4097
4098 // Send down to the second window
4099 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004100 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004101 {pointInFirst, pointInSecond});
4102 mDispatcher->notifyMotion(&secondDownMotionArgs);
4103 // The first window gets a move and the second a down
4104 firstWindow->consumeMotionMove();
4105 secondWindow->consumeMotionDown();
4106
4107 // Send pointer cancel to the second window
4108 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004109 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08004110 {pointInFirst, pointInSecond});
4111 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
4112 mDispatcher->notifyMotion(&pointerUpMotionArgs);
4113 // The first window gets move and the second gets cancel.
4114 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4115 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
4116
4117 // Send up event.
4118 NotifyMotionArgs upMotionArgs =
4119 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4120 ADISPLAY_ID_DEFAULT);
4121 mDispatcher->notifyMotion(&upMotionArgs);
4122 // The first window gets up and the second gets nothing.
4123 firstWindow->consumeMotionUp();
4124 secondWindow->assertNoEvents();
4125}
4126
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004127TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
4128 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4129
4130 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004131 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4133 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
4134 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
4135 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
4136
Harry Cutts33476232023-01-30 19:57:29 +00004137 window->sendTimeline(/*inputEventId=*/1, graphicsTimeline);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00004138 window->assertNoEvents();
4139 mDispatcher->waitForIdle();
4140}
4141
chaviwd1c23182019-12-20 18:44:56 -08004142class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00004143public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004144 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004145 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07004146 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004147 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07004148 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00004149 }
4150
chaviwd1c23182019-12-20 18:44:56 -08004151 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
4152
4153 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4154 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
4155 expectedDisplayId, expectedFlags);
4156 }
4157
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004158 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
4159
4160 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
4161
chaviwd1c23182019-12-20 18:44:56 -08004162 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4163 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
4164 expectedDisplayId, expectedFlags);
4165 }
4166
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004167 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4168 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
4169 expectedDisplayId, expectedFlags);
4170 }
4171
chaviwd1c23182019-12-20 18:44:56 -08004172 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
4173 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
4174 expectedDisplayId, expectedFlags);
4175 }
4176
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004177 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08004178 mInputReceiver->consumeMotionEvent(
4179 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
4180 WithDisplayId(expectedDisplayId),
4181 WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004182 }
4183
Arthur Hungfbfa5722021-11-16 02:45:54 +00004184 void consumeMotionPointerDown(int32_t pointerIdx) {
4185 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
4186 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4187 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004188 /*expectedFlags=*/0);
Arthur Hungfbfa5722021-11-16 02:45:54 +00004189 }
4190
Evan Rosky84f07f02021-04-16 10:42:42 -07004191 MotionEvent* consumeMotion() {
4192 InputEvent* event = mInputReceiver->consume();
4193 if (!event) {
4194 ADD_FAILURE() << "No event was produced";
4195 return nullptr;
4196 }
4197 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
4198 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
4199 return nullptr;
4200 }
4201 return static_cast<MotionEvent*>(event);
4202 }
4203
chaviwd1c23182019-12-20 18:44:56 -08004204 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
4205
4206private:
4207 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00004208};
4209
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004210using InputDispatcherMonitorTest = InputDispatcherTest;
4211
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004212/**
4213 * Two entities that receive touch: A window, and a global monitor.
4214 * The touch goes to the window, and then the window disappears.
4215 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
4216 * for the monitor, as well.
4217 * 1. foregroundWindow
4218 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
4219 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004220TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004221 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4222 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004223 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004224
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004225 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004226
4227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4229 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4230 {100, 200}))
4231 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4232
4233 // Both the foreground window and the global monitor should receive the touch down
4234 window->consumeMotionDown();
4235 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4236
4237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4238 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4239 ADISPLAY_ID_DEFAULT, {110, 200}))
4240 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4241
4242 window->consumeMotionMove();
4243 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4244
4245 // Now the foreground window goes away
4246 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4247 window->consumeMotionCancel();
4248 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
4249
4250 // If more events come in, there will be no more foreground window to send them to. This will
4251 // cause a cancel for the monitor, as well.
4252 ASSERT_EQ(InputEventInjectionResult::FAILED,
4253 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4254 ADISPLAY_ID_DEFAULT, {120, 200}))
4255 << "Injection should fail because the window was removed";
4256 window->assertNoEvents();
4257 // Global monitor now gets the cancel
4258 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4259}
4260
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004261TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07004262 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004263 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4264 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004266
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004267 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004268
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004271 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00004272 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004273 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004274}
4275
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004276TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
4277 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004278
Chris Yea209fde2020-07-22 13:54:51 -07004279 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004280 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4281 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00004283
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00004285 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08004287 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004288 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004289
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004290 // Pilfer pointers from the monitor.
4291 // This should not do anything and the window should continue to receive events.
4292 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00004293
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004295 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4296 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004298
4299 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
4300 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00004301}
4302
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004303TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07004304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004305 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4306 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4308 window->setWindowOffset(20, 40);
4309 window->setWindowTransform(0, 1, -1, 0);
4310
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004311 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07004312
4313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4314 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4315 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4316 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4317 MotionEvent* event = monitor.consumeMotion();
4318 // Even though window has transform, gesture monitor must not.
4319 ASSERT_EQ(ui::Transform(), event->getTransform());
4320}
4321
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004322TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00004323 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004324 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00004325
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004326 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00004327 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004328 << "Injection should fail if there is a monitor, but no touchable window";
4329 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00004330}
4331
chaviw81e2bb92019-12-18 15:03:51 -08004332TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004333 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004334 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4335 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08004336
Arthur Hung72d8dc32020-03-28 00:48:39 +00004337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08004338
4339 NotifyMotionArgs motionArgs =
4340 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4341 ADISPLAY_ID_DEFAULT);
4342
4343 mDispatcher->notifyMotion(&motionArgs);
4344 // Window should receive motion down event.
4345 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4346
4347 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004348 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08004349 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4350 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4351 motionArgs.pointerCoords[0].getX() - 10);
4352
4353 mDispatcher->notifyMotion(&motionArgs);
4354 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004355 /*expectedFlags=*/0);
chaviw81e2bb92019-12-18 15:03:51 -08004356}
4357
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004358/**
4359 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
4360 * the device default right away. In the test scenario, we check both the default value,
4361 * and the action of enabling / disabling.
4362 */
4363TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07004364 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004365 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4366 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004367 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004368
4369 // Set focused application.
4370 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004371 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004372
4373 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00004374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004375 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004376 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004377
4378 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004379 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004381 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004382
4383 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004384 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004385 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004386 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07004387 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004389 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004390 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004391
4392 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07004393 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Harry Cutts33476232023-01-30 19:57:29 +00004395 window->consumeFocusEvent(/*hasFocus=*/false, /*inTouchMode=*/false);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004396
4397 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08004398 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00004399 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00004400 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07004401 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004403 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00004404 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004405
4406 window->assertNoEvents();
4407}
4408
Gang Wange9087892020-01-07 12:17:14 -05004409TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004410 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004411 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4412 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05004413
4414 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004415 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05004416
Arthur Hung72d8dc32020-03-28 00:48:39 +00004417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004418 setFocusedWindow(window);
4419
Harry Cutts33476232023-01-30 19:57:29 +00004420 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Gang Wange9087892020-01-07 12:17:14 -05004421
4422 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4423 mDispatcher->notifyKey(&keyArgs);
4424
4425 InputEvent* event = window->consume();
4426 ASSERT_NE(event, nullptr);
4427
4428 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4429 ASSERT_NE(verified, nullptr);
4430 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
4431
4432 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
4433 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
4434 ASSERT_EQ(keyArgs.source, verified->source);
4435 ASSERT_EQ(keyArgs.displayId, verified->displayId);
4436
4437 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
4438
4439 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05004440 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004441 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05004442 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
4443 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
4444 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
4445 ASSERT_EQ(0, verifiedKey.repeatCount);
4446}
4447
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004448TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07004449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004450 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
4451 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004452
4453 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4454
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004455 ui::Transform transform;
4456 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4457
4458 gui::DisplayInfo displayInfo;
4459 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
4460 displayInfo.transform = transform;
4461
4462 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004463
4464 NotifyMotionArgs motionArgs =
4465 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4466 ADISPLAY_ID_DEFAULT);
4467 mDispatcher->notifyMotion(&motionArgs);
4468
4469 InputEvent* event = window->consume();
4470 ASSERT_NE(event, nullptr);
4471
4472 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
4473 ASSERT_NE(verified, nullptr);
4474 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
4475
4476 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
4477 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
4478 EXPECT_EQ(motionArgs.source, verified->source);
4479 EXPECT_EQ(motionArgs.displayId, verified->displayId);
4480
4481 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
4482
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07004483 const vec2 rawXY =
4484 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
4485 motionArgs.pointerCoords[0].getXYValue());
4486 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
4487 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004488 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004489 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004490 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08004491 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
4492 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
4493}
4494
chaviw09c8d2d2020-08-24 15:48:26 -07004495/**
4496 * Ensure that separate calls to sign the same data are generating the same key.
4497 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
4498 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
4499 * tests.
4500 */
4501TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
4502 KeyEvent event = getTestKeyEvent();
4503 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4504
4505 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
4506 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
4507 ASSERT_EQ(hmac1, hmac2);
4508}
4509
4510/**
4511 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
4512 */
4513TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
4514 KeyEvent event = getTestKeyEvent();
4515 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
4516 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
4517
4518 verifiedEvent.deviceId += 1;
4519 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4520
4521 verifiedEvent.source += 1;
4522 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4523
4524 verifiedEvent.eventTimeNanos += 1;
4525 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4526
4527 verifiedEvent.displayId += 1;
4528 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4529
4530 verifiedEvent.action += 1;
4531 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4532
4533 verifiedEvent.downTimeNanos += 1;
4534 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4535
4536 verifiedEvent.flags += 1;
4537 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4538
4539 verifiedEvent.keyCode += 1;
4540 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4541
4542 verifiedEvent.scanCode += 1;
4543 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4544
4545 verifiedEvent.metaState += 1;
4546 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4547
4548 verifiedEvent.repeatCount += 1;
4549 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
4550}
4551
Vishnu Nair958da932020-08-21 17:12:37 -07004552TEST_F(InputDispatcherTest, SetFocusedWindow) {
4553 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4554 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004555 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004556 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004557 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004558 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4559
4560 // Top window is also focusable but is not granted focus.
4561 windowTop->setFocusable(true);
4562 windowSecond->setFocusable(true);
4563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4564 setFocusedWindow(windowSecond);
4565
4566 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4568 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004569
4570 // Focused window should receive event.
4571 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4572 windowTop->assertNoEvents();
4573}
4574
4575TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
4576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4577 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004578 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004579 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4580
4581 window->setFocusable(true);
4582 // Release channel for window is no longer valid.
4583 window->releaseChannel();
4584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4585 setFocusedWindow(window);
4586
4587 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004588 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4589 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004590
4591 // window channel is invalid, so it should not receive any input event.
4592 window->assertNoEvents();
4593}
4594
4595TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
4596 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4597 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004598 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004599 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07004600 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4601
Vishnu Nair958da932020-08-21 17:12:37 -07004602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4603 setFocusedWindow(window);
4604
4605 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004606 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4607 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004608
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08004609 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07004610 window->assertNoEvents();
4611}
4612
4613TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
4614 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4615 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004616 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004617 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004618 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004619 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4620
4621 windowTop->setFocusable(true);
4622 windowSecond->setFocusable(true);
4623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4624 setFocusedWindow(windowTop);
4625 windowTop->consumeFocusEvent(true);
4626
4627 setFocusedWindow(windowSecond, windowTop);
4628 windowSecond->consumeFocusEvent(true);
4629 windowTop->consumeFocusEvent(false);
4630
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4632 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004633
4634 // Focused window should receive event.
4635 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
4636}
4637
4638TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
4639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4640 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004641 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004642 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004643 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004644 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4645
4646 windowTop->setFocusable(true);
4647 windowSecond->setFocusable(true);
4648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
4649 setFocusedWindow(windowSecond, windowTop);
4650
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004651 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4652 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004653
4654 // Event should be dropped.
4655 windowTop->assertNoEvents();
4656 windowSecond->assertNoEvents();
4657}
4658
4659TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
4660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4661 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004662 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004663 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004664 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
4665 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004666 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4667
4668 window->setFocusable(true);
4669 previousFocusedWindow->setFocusable(true);
4670 window->setVisible(false);
4671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
4672 setFocusedWindow(previousFocusedWindow);
4673 previousFocusedWindow->consumeFocusEvent(true);
4674
4675 // Requesting focus on invisible window takes focus from currently focused window.
4676 setFocusedWindow(window);
4677 previousFocusedWindow->consumeFocusEvent(false);
4678
4679 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00004681 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
4682 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004683
4684 // Window does not get focus event or key down.
4685 window->assertNoEvents();
4686
4687 // Window becomes visible.
4688 window->setVisible(true);
4689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4690
4691 // Window receives focus event.
4692 window->consumeFocusEvent(true);
4693 // Focused window receives key down.
4694 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4695}
4696
Vishnu Nair599f1412021-06-21 10:39:58 -07004697TEST_F(InputDispatcherTest, DisplayRemoved) {
4698 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4699 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004700 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07004701 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4702
4703 // window is granted focus.
4704 window->setFocusable(true);
4705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
4706 setFocusedWindow(window);
4707 window->consumeFocusEvent(true);
4708
4709 // When a display is removed window loses focus.
4710 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
4711 window->consumeFocusEvent(false);
4712}
4713
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004714/**
4715 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
4716 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
4717 * of the 'slipperyEnterWindow'.
4718 *
4719 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
4720 * a way so that the touched location is no longer covered by the top window.
4721 *
4722 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
4723 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
4724 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
4725 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
4726 * with ACTION_DOWN).
4727 * Thus, the touch has been transferred from the top window into the bottom window, because the top
4728 * window moved itself away from the touched location and had Flag::SLIPPERY.
4729 *
4730 * Even though the top window moved away from the touched location, it is still obscuring the bottom
4731 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
4732 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
4733 *
4734 * In this test, we ensure that the event received by the bottom window has
4735 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
4736 */
4737TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004738 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
4739 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004740
4741 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
4742 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4743
4744 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004745 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004746 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004747 // Make sure this one overlaps the bottom window
4748 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
4749 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
4750 // one. Windows with the same owner are not considered to be occluding each other.
4751 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
4752
4753 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004754 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004755 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
4756
4757 mDispatcher->setInputWindows(
4758 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4759
4760 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
4761 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4762 ADISPLAY_ID_DEFAULT, {{50, 50}});
4763 mDispatcher->notifyMotion(&args);
4764 slipperyExitWindow->consumeMotionDown();
4765 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
4766 mDispatcher->setInputWindows(
4767 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
4768
4769 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4770 ADISPLAY_ID_DEFAULT, {{51, 51}});
4771 mDispatcher->notifyMotion(&args);
4772
4773 slipperyExitWindow->consumeMotionCancel();
4774
4775 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
4776 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
4777}
4778
Garfield Tan1c7bc862020-01-28 13:24:04 -08004779class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
4780protected:
4781 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
4782 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
4783
Chris Yea209fde2020-07-22 13:54:51 -07004784 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004785 sp<FakeWindowHandle> mWindow;
4786
4787 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004788 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08004789 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07004790 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004791 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
4792 ASSERT_EQ(OK, mDispatcher->start());
4793
4794 setUpWindow();
4795 }
4796
4797 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07004798 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004799 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004800
Vishnu Nair47074b82020-08-14 11:54:47 -07004801 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004803 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004804 mWindow->consumeFocusEvent(true);
4805 }
4806
Chris Ye2ad95392020-09-01 13:44:44 -07004807 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004808 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004809 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004810 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
4811 mDispatcher->notifyKey(&keyArgs);
4812
4813 // Window should receive key down event.
4814 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4815 }
4816
4817 void expectKeyRepeatOnce(int32_t repeatCount) {
4818 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
4819 InputEvent* repeatEvent = mWindow->consume();
4820 ASSERT_NE(nullptr, repeatEvent);
4821
4822 uint32_t eventType = repeatEvent->getType();
4823 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4824
4825 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4826 uint32_t eventAction = repeatKeyEvent->getAction();
4827 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4828 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4829 }
4830
Chris Ye2ad95392020-09-01 13:44:44 -07004831 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004832 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004833 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004834 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4835 mDispatcher->notifyKey(&keyArgs);
4836
4837 // Window should receive key down event.
4838 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00004839 /*expectedFlags=*/0);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004840 }
4841};
4842
4843TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Harry Cutts33476232023-01-30 19:57:29 +00004844 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004845 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4846 expectKeyRepeatOnce(repeatCount);
4847 }
4848}
4849
4850TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
Harry Cutts33476232023-01-30 19:57:29 +00004851 sendAndConsumeKeyDown(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004852 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4853 expectKeyRepeatOnce(repeatCount);
4854 }
Harry Cutts33476232023-01-30 19:57:29 +00004855 sendAndConsumeKeyDown(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004856 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004857 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4858 expectKeyRepeatOnce(repeatCount);
4859 }
4860}
4861
4862TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004863 sendAndConsumeKeyDown(/*deviceId=*/1);
4864 expectKeyRepeatOnce(/*repeatCount=*/1);
4865 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004866 mWindow->assertNoEvents();
4867}
4868
4869TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004870 sendAndConsumeKeyDown(/*deviceId=*/1);
4871 expectKeyRepeatOnce(/*repeatCount=*/1);
4872 sendAndConsumeKeyDown(/*deviceId=*/2);
4873 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004874 // Stale key up from device 1.
Harry Cutts33476232023-01-30 19:57:29 +00004875 sendAndConsumeKeyUp(/*deviceId=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004876 // Device 2 is still down, keep repeating
Harry Cutts33476232023-01-30 19:57:29 +00004877 expectKeyRepeatOnce(/*repeatCount=*/2);
4878 expectKeyRepeatOnce(/*repeatCount=*/3);
Chris Ye2ad95392020-09-01 13:44:44 -07004879 // Device 2 key up
Harry Cutts33476232023-01-30 19:57:29 +00004880 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004881 mWindow->assertNoEvents();
4882}
4883
4884TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
Harry Cutts33476232023-01-30 19:57:29 +00004885 sendAndConsumeKeyDown(/*deviceId=*/1);
4886 expectKeyRepeatOnce(/*repeatCount=*/1);
4887 sendAndConsumeKeyDown(/*deviceId=*/2);
4888 expectKeyRepeatOnce(/*repeatCount=*/1);
Chris Ye2ad95392020-09-01 13:44:44 -07004889 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
Harry Cutts33476232023-01-30 19:57:29 +00004890 sendAndConsumeKeyUp(/*deviceId=*/2);
Chris Ye2ad95392020-09-01 13:44:44 -07004891 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004892 mWindow->assertNoEvents();
4893}
4894
liushenxiang42232912021-05-21 20:24:09 +08004895TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4896 sendAndConsumeKeyDown(DEVICE_ID);
Harry Cutts33476232023-01-30 19:57:29 +00004897 expectKeyRepeatOnce(/*repeatCount=*/1);
4898 NotifyDeviceResetArgs args(/*id=*/10, /*eventTime=*/20, DEVICE_ID);
liushenxiang42232912021-05-21 20:24:09 +08004899 mDispatcher->notifyDeviceReset(&args);
4900 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4901 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4902 mWindow->assertNoEvents();
4903}
4904
Garfield Tan1c7bc862020-01-28 13:24:04 -08004905TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00004906 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00004907 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004908 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4909 InputEvent* repeatEvent = mWindow->consume();
4910 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4911 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4912 IdGenerator::getSource(repeatEvent->getId()));
4913 }
4914}
4915
4916TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Michael Wrighte1cbbd62023-02-22 19:32:13 +00004917 GTEST_SKIP() << "Flaky test (b/270393106)";
Harry Cutts33476232023-01-30 19:57:29 +00004918 sendAndConsumeKeyDown(/*deviceId=*/1);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004919
4920 std::unordered_set<int32_t> idSet;
4921 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4922 InputEvent* repeatEvent = mWindow->consume();
4923 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4924 int32_t id = repeatEvent->getId();
4925 EXPECT_EQ(idSet.end(), idSet.find(id));
4926 idSet.insert(id);
4927 }
4928}
4929
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004930/* Test InputDispatcher for MultiDisplay */
4931class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4932public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004933 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004934 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004935
Chris Yea209fde2020-07-22 13:54:51 -07004936 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004937 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004938 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004939
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004940 // Set focus window for primary display, but focused display would be second one.
4941 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004942 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004944 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004945 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004946
Chris Yea209fde2020-07-22 13:54:51 -07004947 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004948 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004949 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004950 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004951 // Set focus display to second one.
4952 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4953 // Set focus window for second display.
4954 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004955 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004956 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004957 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004958 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004959 }
4960
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004961 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004962 InputDispatcherTest::TearDown();
4963
Chris Yea209fde2020-07-22 13:54:51 -07004964 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004965 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004966 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004967 windowInSecondary.clear();
4968 }
4969
4970protected:
Chris Yea209fde2020-07-22 13:54:51 -07004971 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004972 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004973 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004974 sp<FakeWindowHandle> windowInSecondary;
4975};
4976
4977TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4978 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4980 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4981 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004982 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004983 windowInSecondary->assertNoEvents();
4984
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004985 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4987 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004989 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004990 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004991}
4992
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004993TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004994 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4996 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004997 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004998 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004999 windowInSecondary->assertNoEvents();
5000
5001 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005003 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08005004 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005005 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08005006
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005007 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005008 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08005009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005010 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005011 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
5012 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08005013
5014 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005015 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005016 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08005017 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005018 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08005019 windowInSecondary->assertNoEvents();
5020}
5021
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005022// Test per-display input monitors for motion event.
5023TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08005024 FakeMonitorReceiver monitorInPrimary =
5025 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5026 FakeMonitorReceiver monitorInSecondary =
5027 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005028
5029 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5031 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5032 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005033 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08005034 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005035 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005036 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005037
5038 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5040 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5041 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005042 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005043 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005044 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08005045 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005046
5047 // Test inject a non-pointer motion event.
5048 // If specific a display, it will dispatch to the focused window of particular display,
5049 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5051 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
5052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005053 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005054 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005055 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005056 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005057}
5058
5059// Test per-display input monitors for key event.
5060TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005061 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08005062 FakeMonitorReceiver monitorInPrimary =
5063 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5064 FakeMonitorReceiver monitorInSecondary =
5065 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005066
5067 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5069 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005070 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08005071 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08005072 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08005073 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005074}
5075
Vishnu Nair958da932020-08-21 17:12:37 -07005076TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
5077 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005078 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07005079 secondWindowInPrimary->setFocusable(true);
5080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
5081 setFocusedWindow(secondWindowInPrimary);
5082 windowInPrimary->consumeFocusEvent(false);
5083 secondWindowInPrimary->consumeFocusEvent(true);
5084
5085 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
5087 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005088 windowInPrimary->assertNoEvents();
5089 windowInSecondary->assertNoEvents();
5090 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5091}
5092
Arthur Hungdfd528e2021-12-08 13:23:04 +00005093TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
5094 FakeMonitorReceiver monitorInPrimary =
5095 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5096 FakeMonitorReceiver monitorInSecondary =
5097 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
5098
5099 // Test touch down on primary display.
5100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5101 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
5102 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5103 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5104 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
5105
5106 // Test touch down on second display.
5107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5108 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
5109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5110 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
5111 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
5112
5113 // Trigger cancel touch.
5114 mDispatcher->cancelCurrentTouch();
5115 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5116 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5117 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
5118 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
5119
5120 // Test inject a move motion event, no window/monitor should receive the event.
5121 ASSERT_EQ(InputEventInjectionResult::FAILED,
5122 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5123 ADISPLAY_ID_DEFAULT, {110, 200}))
5124 << "Inject motion event should return InputEventInjectionResult::FAILED";
5125 windowInPrimary->assertNoEvents();
5126 monitorInPrimary.assertNoEvents();
5127
5128 ASSERT_EQ(InputEventInjectionResult::FAILED,
5129 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5130 SECOND_DISPLAY_ID, {110, 200}))
5131 << "Inject motion event should return InputEventInjectionResult::FAILED";
5132 windowInSecondary->assertNoEvents();
5133 monitorInSecondary.assertNoEvents();
5134}
5135
Jackal Guof9696682018-10-05 12:23:23 +08005136class InputFilterTest : public InputDispatcherTest {
5137protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005138 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
5139 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08005140 NotifyMotionArgs motionArgs;
5141
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005142 motionArgs =
5143 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005144 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005145 motionArgs =
5146 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08005147 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005148 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005149 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005150 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
5151 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08005152 } else {
5153 mFakePolicy->assertFilterInputEventWasNotCalled();
5154 }
5155 }
5156
5157 void testNotifyKey(bool expectToBeFiltered) {
5158 NotifyKeyArgs keyArgs;
5159
5160 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
5161 mDispatcher->notifyKey(&keyArgs);
5162 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
5163 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005164 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08005165
5166 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08005167 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08005168 } else {
5169 mFakePolicy->assertFilterInputEventWasNotCalled();
5170 }
5171 }
5172};
5173
5174// Test InputFilter for MotionEvent
5175TEST_F(InputFilterTest, MotionEvent_InputFilter) {
5176 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
5177 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5178 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5179
5180 // Enable InputFilter
5181 mDispatcher->setInputFilterEnabled(true);
5182 // Test touch on both primary and second display, and check if both events are filtered.
5183 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
5184 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
5185
5186 // Disable InputFilter
5187 mDispatcher->setInputFilterEnabled(false);
5188 // Test touch on both primary and second display, and check if both events aren't filtered.
5189 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
5190 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
5191}
5192
5193// Test InputFilter for KeyEvent
5194TEST_F(InputFilterTest, KeyEvent_InputFilter) {
5195 // Since the InputFilter is disabled by default, check if key event aren't filtered.
5196 testNotifyKey(/*expectToBeFiltered*/ false);
5197
5198 // Enable InputFilter
5199 mDispatcher->setInputFilterEnabled(true);
5200 // Send a key event, and check if it is filtered.
5201 testNotifyKey(/*expectToBeFiltered*/ true);
5202
5203 // Disable InputFilter
5204 mDispatcher->setInputFilterEnabled(false);
5205 // Send a key event, and check if it isn't filtered.
5206 testNotifyKey(/*expectToBeFiltered*/ false);
5207}
5208
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005209// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
5210// logical display coordinate space.
5211TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
5212 ui::Transform firstDisplayTransform;
5213 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
5214 ui::Transform secondDisplayTransform;
5215 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
5216
5217 std::vector<gui::DisplayInfo> displayInfos(2);
5218 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
5219 displayInfos[0].transform = firstDisplayTransform;
5220 displayInfos[1].displayId = SECOND_DISPLAY_ID;
5221 displayInfos[1].transform = secondDisplayTransform;
5222
5223 mDispatcher->onWindowInfosChanged({}, displayInfos);
5224
5225 // Enable InputFilter
5226 mDispatcher->setInputFilterEnabled(true);
5227
5228 // Ensure the correct transforms are used for the displays.
5229 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
5230 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
5231}
5232
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005233class InputFilterInjectionPolicyTest : public InputDispatcherTest {
5234protected:
5235 virtual void SetUp() override {
5236 InputDispatcherTest::SetUp();
5237
5238 /**
5239 * We don't need to enable input filter to test the injected event policy, but we enabled it
5240 * here to make the tests more realistic, since this policy only matters when inputfilter is
5241 * on.
5242 */
5243 mDispatcher->setInputFilterEnabled(true);
5244
5245 std::shared_ptr<InputApplicationHandle> application =
5246 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005247 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
5248 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005249
5250 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5251 mWindow->setFocusable(true);
5252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5253 setFocusedWindow(mWindow);
5254 mWindow->consumeFocusEvent(true);
5255 }
5256
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005257 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5258 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005259 KeyEvent event;
5260
5261 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5262 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
5263 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
Harry Cutts33476232023-01-30 19:57:29 +00005264 KEY_A, AMETA_NONE, /*repeatCount=*/0, eventTime, eventTime);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005265 const int32_t additionalPolicyFlags =
5266 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
5267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005268 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005269 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5270 policyFlags | additionalPolicyFlags));
5271
5272 InputEvent* received = mWindow->consume();
5273 ASSERT_NE(nullptr, received);
5274 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005275 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
5276 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
5277 ASSERT_EQ(flags, keyEvent.getFlags());
5278 }
5279
5280 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
5281 int32_t flags) {
5282 MotionEvent event;
5283 PointerProperties pointerProperties[1];
5284 PointerCoords pointerCoords[1];
5285 pointerProperties[0].clear();
5286 pointerProperties[0].id = 0;
5287 pointerCoords[0].clear();
5288 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
5289 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
5290
5291 ui::Transform identityTransform;
5292 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
5293 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
5294 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
5295 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
5296 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07005297 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07005298 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005299 /*pointerCount*/ 1, pointerProperties, pointerCoords);
5300
5301 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
5302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00005303 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005304 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
5305 policyFlags | additionalPolicyFlags));
5306
5307 InputEvent* received = mWindow->consume();
5308 ASSERT_NE(nullptr, received);
5309 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
5310 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
5311 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
5312 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005313 }
5314
5315private:
5316 sp<FakeWindowHandle> mWindow;
5317};
5318
5319TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005320 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
5321 // filter. Without it, the event will no different from a regularly injected event, and the
5322 // injected device id will be overwritten.
Harry Cutts33476232023-01-30 19:57:29 +00005323 testInjectedKey(POLICY_FLAG_FILTERED, /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
5324 /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005325}
5326
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005327TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005328 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005329 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005330 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
5331}
5332
5333TEST_F(InputFilterInjectionPolicyTest,
5334 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
5335 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Harry Cutts33476232023-01-30 19:57:29 +00005336 /*injectedDeviceId=*/3, /*resolvedDeviceId=*/3,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00005337 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005338}
5339
5340TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
Harry Cutts33476232023-01-30 19:57:29 +00005341 testInjectedKey(/*policyFlags=*/0, /*injectedDeviceId=*/3,
5342 /*resolvedDeviceId=*/VIRTUAL_KEYBOARD_ID, /*flags=*/0);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00005343}
5344
chaviwfd6d3512019-03-25 13:23:49 -07005345class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005346 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07005347 InputDispatcherTest::SetUp();
5348
Chris Yea209fde2020-07-22 13:54:51 -07005349 std::shared_ptr<FakeApplicationHandle> application =
5350 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005351 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005352 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005353 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07005354
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005355 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005356 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005357 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07005358
5359 // Set focused application.
5360 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07005361 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07005362
5363 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005365 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005366 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07005367 }
5368
Prabir Pradhan3608aad2019-10-02 17:08:26 -07005369 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07005370 InputDispatcherTest::TearDown();
5371
5372 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005373 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07005374 }
5375
5376protected:
5377 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005378 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005379 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07005380};
5381
5382// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5383// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
5384// the onPointerDownOutsideFocus callback.
5385TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005387 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5388 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005389 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005390 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005391
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005392 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07005393 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
5394}
5395
5396// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
5397// DOWN on the window that doesn't have focus. Ensure no window received the
5398// onPointerDownOutsideFocus callback.
5399TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005403 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005404
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005405 ASSERT_TRUE(mDispatcher->waitForIdle());
5406 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005407}
5408
5409// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
5410// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
5411TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5413 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005414 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005415 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07005416
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005417 ASSERT_TRUE(mDispatcher->waitForIdle());
5418 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005419}
5420
5421// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
5422// DOWN on the window that already has focus. Ensure no window received the
5423// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10005424TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08005426 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07005427 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07005429 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07005430
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005431 ASSERT_TRUE(mDispatcher->waitForIdle());
5432 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07005433}
5434
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005435// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
5436// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
5437TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
5438 const MotionEvent event =
5439 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
5440 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00005441 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08005442 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
5443 .build();
5444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
5445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5446 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
5447
5448 ASSERT_TRUE(mDispatcher->waitForIdle());
5449 mFakePolicy->assertOnPointerDownWasNotCalled();
5450 // Ensure that the unfocused window did not receive any FOCUS events.
5451 mUnfocusedWindow->assertNoEvents();
5452}
5453
chaviwaf87b3e2019-10-01 16:59:28 -07005454// These tests ensures we can send touch events to a single client when there are multiple input
5455// windows that point to the same client token.
5456class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
5457 virtual void SetUp() override {
5458 InputDispatcherTest::SetUp();
5459
Chris Yea209fde2020-07-22 13:54:51 -07005460 std::shared_ptr<FakeApplicationHandle> application =
5461 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005462 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
5463 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07005464 mWindow1->setFrame(Rect(0, 0, 100, 100));
5465
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005466 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
5467 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07005468 mWindow2->setFrame(Rect(100, 100, 200, 200));
5469
Arthur Hung72d8dc32020-03-28 00:48:39 +00005470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07005471 }
5472
5473protected:
5474 sp<FakeWindowHandle> mWindow1;
5475 sp<FakeWindowHandle> mWindow2;
5476
5477 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05005478 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07005479 vec2 vals = windowInfo->transform.transform(point.x, point.y);
5480 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07005481 }
5482
5483 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
5484 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01005485 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07005486 InputEvent* event = window->consume();
5487
5488 ASSERT_NE(nullptr, event) << name.c_str()
5489 << ": consumer should have returned non-NULL event.";
5490
5491 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
5492 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
5493 << " event, got " << inputEventTypeToString(event->getType()) << " event";
5494
5495 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005496 assertMotionAction(expectedAction, motionEvent.getAction());
Siarhei Vishniakoue9349e72022-12-02 11:39:20 -08005497 ASSERT_EQ(points.size(), motionEvent.getPointerCount());
chaviwaf87b3e2019-10-01 16:59:28 -07005498
5499 for (size_t i = 0; i < points.size(); i++) {
5500 float expectedX = points[i].x;
5501 float expectedY = points[i].y;
5502
5503 EXPECT_EQ(expectedX, motionEvent.getX(i))
5504 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
5505 << ", got " << motionEvent.getX(i);
5506 EXPECT_EQ(expectedY, motionEvent.getY(i))
5507 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
5508 << ", got " << motionEvent.getY(i);
5509 }
5510 }
chaviw9eaa22c2020-07-01 16:21:27 -07005511
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08005512 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07005513 std::vector<PointF> expectedPoints) {
5514 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
5515 ADISPLAY_ID_DEFAULT, touchedPoints);
5516 mDispatcher->notifyMotion(&motionArgs);
5517
5518 // Always consume from window1 since it's the window that has the InputReceiver
5519 consumeMotionEvent(mWindow1, action, expectedPoints);
5520 }
chaviwaf87b3e2019-10-01 16:59:28 -07005521};
5522
5523TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
5524 // Touch Window 1
5525 PointF touchedPoint = {10, 10};
5526 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005527 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005528
5529 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005530 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005531
5532 // Touch Window 2
5533 touchedPoint = {150, 150};
5534 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005535 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005536}
5537
chaviw9eaa22c2020-07-01 16:21:27 -07005538TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
5539 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07005540 mWindow2->setWindowScale(0.5f, 0.5f);
5541
5542 // Touch Window 1
5543 PointF touchedPoint = {10, 10};
5544 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005545 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005546 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07005547 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005548
5549 // Touch Window 2
5550 touchedPoint = {150, 150};
5551 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07005552 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
5553 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005554
chaviw9eaa22c2020-07-01 16:21:27 -07005555 // Update the transform so rotation is set
5556 mWindow2->setWindowTransform(0, -1, 1, 0);
5557 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
5558 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07005559}
5560
chaviw9eaa22c2020-07-01 16:21:27 -07005561TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005562 mWindow2->setWindowScale(0.5f, 0.5f);
5563
5564 // Touch Window 1
5565 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5566 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005567 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005568
5569 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005570 touchedPoints.push_back(PointF{150, 150});
5571 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005572 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005573
chaviw9eaa22c2020-07-01 16:21:27 -07005574 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005575 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005576 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005577
chaviw9eaa22c2020-07-01 16:21:27 -07005578 // Update the transform so rotation is set for Window 2
5579 mWindow2->setWindowTransform(0, -1, 1, 0);
5580 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005581 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005582}
5583
chaviw9eaa22c2020-07-01 16:21:27 -07005584TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005585 mWindow2->setWindowScale(0.5f, 0.5f);
5586
5587 // Touch Window 1
5588 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5589 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005590 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005591
5592 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005593 touchedPoints.push_back(PointF{150, 150});
5594 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005595
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005596 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005597
5598 // Move both windows
5599 touchedPoints = {{20, 20}, {175, 175}};
5600 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5601 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5602
chaviw9eaa22c2020-07-01 16:21:27 -07005603 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005604
chaviw9eaa22c2020-07-01 16:21:27 -07005605 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005606 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005607 expectedPoints.pop_back();
5608
5609 // Touch Window 2
5610 mWindow2->setWindowTransform(0, -1, 1, 0);
5611 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005612 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07005613
5614 // Move both windows
5615 touchedPoints = {{20, 20}, {175, 175}};
5616 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5617 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5618
5619 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005620}
5621
5622TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
5623 mWindow1->setWindowScale(0.5f, 0.5f);
5624
5625 // Touch Window 1
5626 std::vector<PointF> touchedPoints = {PointF{10, 10}};
5627 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07005628 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005629
5630 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07005631 touchedPoints.push_back(PointF{150, 150});
5632 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005633
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005634 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005635
5636 // Move both windows
5637 touchedPoints = {{20, 20}, {175, 175}};
5638 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
5639 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
5640
chaviw9eaa22c2020-07-01 16:21:27 -07005641 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00005642}
5643
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005644class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
5645 virtual void SetUp() override {
5646 InputDispatcherTest::SetUp();
5647
Chris Yea209fde2020-07-22 13:54:51 -07005648 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005649 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005650 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
5651 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005652 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005653 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07005654 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005655
5656 // Set focused application.
5657 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
5658
5659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005660 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005661 mWindow->consumeFocusEvent(true);
5662 }
5663
5664 virtual void TearDown() override {
5665 InputDispatcherTest::TearDown();
5666 mWindow.clear();
5667 }
5668
5669protected:
Chris Yea209fde2020-07-22 13:54:51 -07005670 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005671 sp<FakeWindowHandle> mWindow;
5672 static constexpr PointF WINDOW_LOCATION = {20, 20};
5673
5674 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005676 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5677 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005679 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5680 WINDOW_LOCATION));
5681 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005682
5683 sp<FakeWindowHandle> addSpyWindow() {
5684 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005685 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005686 spy->setTrustedOverlay(true);
5687 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005688 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005689 spy->setDispatchingTimeout(30ms);
5690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
5691 return spy;
5692 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005693};
5694
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005695// Send a tap and respond, which should not cause an ANR.
5696TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
5697 tapOnWindow();
5698 mWindow->consumeMotionDown();
5699 mWindow->consumeMotionUp();
5700 ASSERT_TRUE(mDispatcher->waitForIdle());
5701 mFakePolicy->assertNotifyAnrWasNotCalled();
5702}
5703
5704// Send a regular key and respond, which should not cause an ANR.
5705TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005707 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5708 ASSERT_TRUE(mDispatcher->waitForIdle());
5709 mFakePolicy->assertNotifyAnrWasNotCalled();
5710}
5711
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005712TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
5713 mWindow->setFocusable(false);
5714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5715 mWindow->consumeFocusEvent(false);
5716
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005717 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005718 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5719 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
5720 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005722 // Key will not go to window because we have no focused window.
5723 // The 'no focused window' ANR timer should start instead.
5724
5725 // Now, the focused application goes away.
5726 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
5727 // The key should get dropped and there should be no ANR.
5728
5729 ASSERT_TRUE(mDispatcher->waitForIdle());
5730 mFakePolicy->assertNotifyAnrWasNotCalled();
5731}
5732
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005733// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005734// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
5735// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005736TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005737 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005738 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5739 WINDOW_LOCATION));
5740
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005741 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
5742 ASSERT_TRUE(sequenceNum);
5743 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005744 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005746 mWindow->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005747 mWindow->consumeMotionEvent(
5748 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005749 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005750 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005751}
5752
5753// Send a key to the app and have the app not respond right away.
5754TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
5755 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005757 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
5758 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005759 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005760 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005761 ASSERT_TRUE(mDispatcher->waitForIdle());
5762}
5763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005764// We have a focused application, but no focused window
5765TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005766 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5768 mWindow->consumeFocusEvent(false);
5769
5770 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005772 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5773 WINDOW_LOCATION));
5774 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
5775 mDispatcher->waitForIdle();
5776 mFakePolicy->assertNotifyAnrWasNotCalled();
5777
5778 // Once a focused event arrives, we get an ANR for this application
5779 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5780 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005781 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005782 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5783 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005784 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005785 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07005786 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005787 ASSERT_TRUE(mDispatcher->waitForIdle());
5788}
5789
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005790/**
5791 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
5792 * there will not be an ANR.
5793 */
5794TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
5795 mWindow->setFocusable(false);
5796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5797 mWindow->consumeFocusEvent(false);
5798
5799 KeyEvent event;
5800 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
5801 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
5802
5803 // Define a valid key down event that is stale (too old).
5804 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
5805 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
Harry Cutts33476232023-01-30 19:57:29 +00005806 AMETA_NONE, /*repeatCount=*/1, eventTime, eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005807
5808 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
5809
5810 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005811 mDispatcher->injectInputEvent(&event, /*targetUid=*/{},
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08005812 InputEventInjectionSync::WAIT_FOR_RESULT,
5813 INJECT_EVENT_TIMEOUT, policyFlags);
5814 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
5815 << "Injection should fail because the event is stale";
5816
5817 ASSERT_TRUE(mDispatcher->waitForIdle());
5818 mFakePolicy->assertNotifyAnrWasNotCalled();
5819 mWindow->assertNoEvents();
5820}
5821
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005822// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005823// Make sure that we don't notify policy twice about the same ANR.
5824TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005825 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5827 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005828
5829 // Once a focused event arrives, we get an ANR for this application
5830 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5831 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005832 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005833 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
5834 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005835 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005836 const std::chrono::duration appTimeout =
5837 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5838 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005839
Vishnu Naire4df8752022-09-08 09:17:55 -07005840 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005841 // ANR should not be raised again. It is up to policy to do that if it desires.
5842 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005843
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005844 // If we now get a focused window, the ANR should stop, but the policy handles that via
5845 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 ASSERT_TRUE(mDispatcher->waitForIdle());
5847}
5848
5849// We have a focused application, but no focused window
5850TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005851 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5853 mWindow->consumeFocusEvent(false);
5854
5855 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005856 const InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00005857 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005858 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5859 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005860
Vishnu Naire4df8752022-09-08 09:17:55 -07005861 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5862 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005863
5864 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005865 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005866 ASSERT_TRUE(mDispatcher->waitForIdle());
5867 mWindow->assertNoEvents();
5868}
5869
5870/**
5871 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5872 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5873 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5874 * the ANR mechanism should still work.
5875 *
5876 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5877 * DOWN event, while not responding on the second one.
5878 */
5879TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5880 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5881 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5882 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5883 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5884 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005885 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886
5887 // Now send ACTION_UP, with identical timestamp
5888 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5889 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5890 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5891 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005892 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005893
5894 // We have now sent down and up. Let's consume first event and then ANR on the second.
5895 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5896 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005897 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898}
5899
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005900// A spy window can receive an ANR
5901TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5902 sp<FakeWindowHandle> spy = addSpyWindow();
5903
5904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5906 WINDOW_LOCATION));
5907 mWindow->consumeMotionDown();
5908
5909 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5910 ASSERT_TRUE(sequenceNum);
5911 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005912 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005913
5914 spy->finishEvent(*sequenceNum);
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08005915 spy->consumeMotionEvent(
5916 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005917 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005918 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005919}
5920
5921// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005922// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005923TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5924 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005925
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5927 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005928 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005930
5931 // Stuck on the ACTION_UP
5932 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005933 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005935 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005936 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005937 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5938 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005939
5940 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5941 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005942 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005943 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005944 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005945}
5946
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005947// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005948// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005949TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5950 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005951
5952 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005953 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5954 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005955
5956 mWindow->consumeMotionDown();
5957 // Stuck on the ACTION_UP
5958 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005959 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005960
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005961 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005962 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005963 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5964 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005965
5966 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5967 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005968 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005969 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005970 spy->assertNoEvents();
5971}
5972
5973TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5974 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5975
5976 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5977
5978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5979 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5980 WINDOW_LOCATION));
5981
5982 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5983 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5984 ASSERT_TRUE(consumeSeq);
5985
Prabir Pradhanedd96402022-02-15 01:46:16 -08005986 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005987
5988 monitor.finishEvent(*consumeSeq);
5989 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5990
5991 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005992 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005993}
5994
5995// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5996// process events, you don't get an anr. When the window later becomes unresponsive again, you
5997// get an ANR again.
5998// 1. tap -> block on ACTION_UP -> receive ANR
5999// 2. consume all pending events (= queue becomes healthy again)
6000// 3. tap again -> block on ACTION_UP again -> receive ANR second time
6001TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
6002 tapOnWindow();
6003
6004 mWindow->consumeMotionDown();
6005 // Block on ACTION_UP
6006 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006007 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006008 mWindow->consumeMotionUp(); // Now the connection should be healthy again
6009 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006010 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006011 mWindow->assertNoEvents();
6012
6013 tapOnWindow();
6014 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006016 mWindow->consumeMotionUp();
6017
6018 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006019 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006020 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006021 mWindow->assertNoEvents();
6022}
6023
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006024// If a connection remains unresponsive for a while, make sure policy is only notified once about
6025// it.
6026TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006028 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6029 WINDOW_LOCATION));
6030
6031 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006032 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006033 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006034 // 'notifyConnectionUnresponsive' should only be called once per connection
6035 mFakePolicy->assertNotifyAnrWasNotCalled();
6036 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006037 mWindow->consumeMotionDown();
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08006038 mWindow->consumeMotionEvent(
6039 AllOf(WithMotionAction(ACTION_CANCEL), WithDisplayId(ADISPLAY_ID_DEFAULT)));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006040 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006041 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006042 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006043 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006044}
6045
6046/**
6047 * If a window is processing a motion event, and then a key event comes in, the key event should
6048 * not to to the focused window until the motion is processed.
6049 *
6050 * Warning!!!
6051 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6052 * and the injection timeout that we specify when injecting the key.
6053 * We must have the injection timeout (10ms) be smaller than
6054 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6055 *
6056 * If that value changes, this test should also change.
6057 */
6058TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
6059 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6061
6062 tapOnWindow();
6063 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6064 ASSERT_TRUE(downSequenceNum);
6065 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6066 ASSERT_TRUE(upSequenceNum);
6067 // Don't finish the events yet, and send a key
6068 // Injection will "succeed" because we will eventually give up and send the key to the focused
6069 // window even if motions are still being processed. But because the injection timeout is short,
6070 // we will receive INJECTION_TIMED_OUT as the result.
6071
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006072 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006073 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006074 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
6075 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006076 // Key will not be sent to the window, yet, because the window is still processing events
6077 // and the key remains pending, waiting for the touch events to be processed
6078 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6079 ASSERT_FALSE(keySequenceNum);
6080
6081 std::this_thread::sleep_for(500ms);
6082 // if we wait long enough though, dispatcher will give up, and still send the key
6083 // to the focused window, even though we have not yet finished the motion event
6084 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6085 mWindow->finishEvent(*downSequenceNum);
6086 mWindow->finishEvent(*upSequenceNum);
6087}
6088
6089/**
6090 * If a window is processing a motion event, and then a key event comes in, the key event should
6091 * not go to the focused window until the motion is processed.
6092 * If then a new motion comes in, then the pending key event should be going to the currently
6093 * focused window right away.
6094 */
6095TEST_F(InputDispatcherSingleWindowAnr,
6096 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
6097 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
6098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6099
6100 tapOnWindow();
6101 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
6102 ASSERT_TRUE(downSequenceNum);
6103 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
6104 ASSERT_TRUE(upSequenceNum);
6105 // Don't finish the events yet, and send a key
6106 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006108 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6109 InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006110 // At this point, key is still pending, and should not be sent to the application yet.
6111 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
6112 ASSERT_FALSE(keySequenceNum);
6113
6114 // Now tap down again. It should cause the pending key to go to the focused window right away.
6115 tapOnWindow();
6116 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
6117 // the other events yet. We can finish events in any order.
6118 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
6119 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
6120 mWindow->consumeMotionDown();
6121 mWindow->consumeMotionUp();
6122 mWindow->assertNoEvents();
6123}
6124
6125class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
6126 virtual void SetUp() override {
6127 InputDispatcherTest::SetUp();
6128
Chris Yea209fde2020-07-22 13:54:51 -07006129 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006130 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006131 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
6132 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006133 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006134 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006135 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006136
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006137 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
6138 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05006139 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006140 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006141
6142 // Set focused application.
6143 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07006144 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006145
6146 // Expect one focus window exist in display.
6147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006148 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006149 mFocusedWindow->consumeFocusEvent(true);
6150 }
6151
6152 virtual void TearDown() override {
6153 InputDispatcherTest::TearDown();
6154
6155 mUnfocusedWindow.clear();
6156 mFocusedWindow.clear();
6157 }
6158
6159protected:
Chris Yea209fde2020-07-22 13:54:51 -07006160 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006161 sp<FakeWindowHandle> mUnfocusedWindow;
6162 sp<FakeWindowHandle> mFocusedWindow;
6163 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
6164 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
6165 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
6166
6167 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
6168
6169 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
6170
6171private:
6172 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6175 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006177 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6178 location));
6179 }
6180};
6181
6182// If we have 2 windows that are both unresponsive, the one with the shortest timeout
6183// should be ANR'd first.
6184TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006186 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6187 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006188 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006189 mFocusedWindow->consumeMotionDown();
6190 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006191 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006192 // We consumed all events, so no ANR
6193 ASSERT_TRUE(mDispatcher->waitForIdle());
6194 mFakePolicy->assertNotifyAnrWasNotCalled();
6195
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006197 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6198 FOCUSED_WINDOW_LOCATION));
6199 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
6200 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006201
6202 const std::chrono::duration timeout =
6203 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006204 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006205 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
6206 // sequence to make it consistent
6207 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006209 mFocusedWindow->consumeMotionDown();
6210 // This cancel is generated because the connection was unresponsive
6211 mFocusedWindow->consumeMotionCancel();
6212 mFocusedWindow->assertNoEvents();
6213 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006214 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006215 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6216 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006217 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006218}
6219
6220// If we have 2 windows with identical timeouts that are both unresponsive,
6221// it doesn't matter which order they should have ANR.
6222// But we should receive ANR for both.
6223TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
6224 // Set the timeout for unfocused window to match the focused window
6225 mUnfocusedWindow->setDispatchingTimeout(10ms);
6226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6227
6228 tapOnFocusedWindow();
6229 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08006230 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
6231 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
6232 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006233
6234 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006235 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
6236 mFocusedWindow->getToken() == anrConnectionToken2);
6237 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
6238 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006239
6240 ASSERT_TRUE(mDispatcher->waitForIdle());
6241 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006242
6243 mFocusedWindow->consumeMotionDown();
6244 mFocusedWindow->consumeMotionUp();
6245 mUnfocusedWindow->consumeMotionOutside();
6246
Prabir Pradhanedd96402022-02-15 01:46:16 -08006247 sp<IBinder> responsiveToken1, responsiveToken2;
6248 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
6249 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006250
6251 // Both applications should be marked as responsive, in any order
6252 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
6253 mFocusedWindow->getToken() == responsiveToken2);
6254 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
6255 mUnfocusedWindow->getToken() == responsiveToken2);
6256 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006257}
6258
6259// If a window is already not responding, the second tap on the same window should be ignored.
6260// We should also log an error to account for the dropped event (not tested here).
6261// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
6262TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
6263 tapOnFocusedWindow();
6264 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006265 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006266 // Receive the events, but don't respond
6267 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
6268 ASSERT_TRUE(downEventSequenceNum);
6269 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
6270 ASSERT_TRUE(upEventSequenceNum);
6271 const std::chrono::duration timeout =
6272 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006273 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006274
6275 // Tap once again
6276 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006277 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006278 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6279 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006280 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006281 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6282 FOCUSED_WINDOW_LOCATION));
6283 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
6284 // valid touch target
6285 mUnfocusedWindow->assertNoEvents();
6286
6287 // Consume the first tap
6288 mFocusedWindow->finishEvent(*downEventSequenceNum);
6289 mFocusedWindow->finishEvent(*upEventSequenceNum);
6290 ASSERT_TRUE(mDispatcher->waitForIdle());
6291 // The second tap did not go to the focused window
6292 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006293 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08006294 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6295 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006296 mFakePolicy->assertNotifyAnrWasNotCalled();
6297}
6298
6299// If you tap outside of all windows, there will not be ANR
6300TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006301 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6303 LOCATION_OUTSIDE_ALL_WINDOWS));
6304 ASSERT_TRUE(mDispatcher->waitForIdle());
6305 mFakePolicy->assertNotifyAnrWasNotCalled();
6306}
6307
6308// Since the focused window is paused, tapping on it should not produce any events
6309TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
6310 mFocusedWindow->setPaused(true);
6311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
6312
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006313 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6315 FOCUSED_WINDOW_LOCATION));
6316
6317 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
6318 ASSERT_TRUE(mDispatcher->waitForIdle());
6319 // Should not ANR because the window is paused, and touches shouldn't go to it
6320 mFakePolicy->assertNotifyAnrWasNotCalled();
6321
6322 mFocusedWindow->assertNoEvents();
6323 mUnfocusedWindow->assertNoEvents();
6324}
6325
6326/**
6327 * If a window is processing a motion event, and then a key event comes in, the key event should
6328 * not to to the focused window until the motion is processed.
6329 * If a different window becomes focused at this time, the key should go to that window instead.
6330 *
6331 * Warning!!!
6332 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
6333 * and the injection timeout that we specify when injecting the key.
6334 * We must have the injection timeout (10ms) be smaller than
6335 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
6336 *
6337 * If that value changes, this test should also change.
6338 */
6339TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
6340 // Set a long ANR timeout to prevent it from triggering
6341 mFocusedWindow->setDispatchingTimeout(2s);
6342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6343
6344 tapOnUnfocusedWindow();
6345 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
6346 ASSERT_TRUE(downSequenceNum);
6347 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
6348 ASSERT_TRUE(upSequenceNum);
6349 // Don't finish the events yet, and send a key
6350 // Injection will succeed because we will eventually give up and send the key to the focused
6351 // window even if motions are still being processed.
6352
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006353 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006354 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6355 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006357 // Key will not be sent to the window, yet, because the window is still processing events
6358 // and the key remains pending, waiting for the touch events to be processed
6359 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
6360 ASSERT_FALSE(keySequenceNum);
6361
6362 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07006363 mFocusedWindow->setFocusable(false);
6364 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07006366 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006367
6368 // Focus events should precede the key events
6369 mUnfocusedWindow->consumeFocusEvent(true);
6370 mFocusedWindow->consumeFocusEvent(false);
6371
6372 // Finish the tap events, which should unblock dispatcher
6373 mUnfocusedWindow->finishEvent(*downSequenceNum);
6374 mUnfocusedWindow->finishEvent(*upSequenceNum);
6375
6376 // Now that all queues are cleared and no backlog in the connections, the key event
6377 // can finally go to the newly focused "mUnfocusedWindow".
6378 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6379 mFocusedWindow->assertNoEvents();
6380 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006381 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006382}
6383
6384// When the touch stream is split across 2 windows, and one of them does not respond,
6385// then ANR should be raised and the touch should be canceled for the unresponsive window.
6386// The other window should not be affected by that.
6387TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
6388 // Touch Window 1
6389 NotifyMotionArgs motionArgs =
6390 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6391 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
6392 mDispatcher->notifyMotion(&motionArgs);
6393 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
Harry Cutts33476232023-01-30 19:57:29 +00006394 ADISPLAY_ID_DEFAULT, /*flags=*/0);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006395
6396 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006397 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6398 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006399 mDispatcher->notifyMotion(&motionArgs);
6400
6401 const std::chrono::duration timeout =
6402 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006403 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006404
6405 mUnfocusedWindow->consumeMotionDown();
6406 mFocusedWindow->consumeMotionDown();
6407 // Focused window may or may not receive ACTION_MOVE
6408 // But it should definitely receive ACTION_CANCEL due to the ANR
6409 InputEvent* event;
6410 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
6411 ASSERT_TRUE(moveOrCancelSequenceNum);
6412 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
6413 ASSERT_NE(nullptr, event);
6414 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
6415 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
6416 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
6417 mFocusedWindow->consumeMotionCancel();
6418 } else {
6419 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
6420 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006421 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006422 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
6423 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006424
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006425 mUnfocusedWindow->assertNoEvents();
6426 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006427 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006428}
6429
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006430/**
6431 * If we have no focused window, and a key comes in, we start the ANR timer.
6432 * The focused application should add a focused window before the timer runs out to prevent ANR.
6433 *
6434 * If the user touches another application during this time, the key should be dropped.
6435 * Next, if a new focused window comes in, without toggling the focused application,
6436 * then no ANR should occur.
6437 *
6438 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
6439 * but in some cases the policy may not update the focused application.
6440 */
6441TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
6442 std::shared_ptr<FakeApplicationHandle> focusedApplication =
6443 std::make_shared<FakeApplicationHandle>();
6444 focusedApplication->setDispatchingTimeout(60ms);
6445 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
6446 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
6447 mFocusedWindow->setFocusable(false);
6448
6449 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6450 mFocusedWindow->consumeFocusEvent(false);
6451
6452 // Send a key. The ANR timer should start because there is no focused window.
6453 // 'focusedApplication' will get blamed if this timer completes.
6454 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006455 InputEventInjectionResult result =
Harry Cutts33476232023-01-30 19:57:29 +00006456 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6457 InputEventInjectionSync::NONE, /*injectionTimeout=*/10ms,
6458 /*allowKeyRepeat=*/false);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05006460
6461 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
6462 // then the injected touches won't cause the focused event to get dropped.
6463 // The dispatcher only checks for whether the queue should be pruned upon queueing.
6464 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
6465 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
6466 // For this test, it means that the key would get delivered to the window once it becomes
6467 // focused.
6468 std::this_thread::sleep_for(10ms);
6469
6470 // Touch unfocused window. This should force the pending key to get dropped.
6471 NotifyMotionArgs motionArgs =
6472 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6473 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
6474 mDispatcher->notifyMotion(&motionArgs);
6475
6476 // We do not consume the motion right away, because that would require dispatcher to first
6477 // process (== drop) the key event, and by that time, ANR will be raised.
6478 // Set the focused window first.
6479 mFocusedWindow->setFocusable(true);
6480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
6481 setFocusedWindow(mFocusedWindow);
6482 mFocusedWindow->consumeFocusEvent(true);
6483 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
6484 // to another application. This could be a bug / behaviour in the policy.
6485
6486 mUnfocusedWindow->consumeMotionDown();
6487
6488 ASSERT_TRUE(mDispatcher->waitForIdle());
6489 // Should not ANR because we actually have a focused window. It was just added too slowly.
6490 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
6491}
6492
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006493// These tests ensure we cannot send touch events to a window that's positioned behind a window
6494// that has feature NO_INPUT_CHANNEL.
6495// Layout:
6496// Top (closest to user)
6497// mNoInputWindow (above all windows)
6498// mBottomWindow
6499// Bottom (furthest from user)
6500class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
6501 virtual void SetUp() override {
6502 InputDispatcherTest::SetUp();
6503
6504 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006505 mNoInputWindow =
6506 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6507 "Window without input channel", ADISPLAY_ID_DEFAULT,
Harry Cutts33476232023-01-30 19:57:29 +00006508 /*token=*/std::make_optional<sp<IBinder>>(nullptr));
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006509 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006510 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6511 // It's perfectly valid for this window to not have an associated input channel
6512
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006513 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
6514 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006515 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
6516
6517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6518 }
6519
6520protected:
6521 std::shared_ptr<FakeApplicationHandle> mApplication;
6522 sp<FakeWindowHandle> mNoInputWindow;
6523 sp<FakeWindowHandle> mBottomWindow;
6524};
6525
6526TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
6527 PointF touchedPoint = {10, 10};
6528
6529 NotifyMotionArgs motionArgs =
6530 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6531 ADISPLAY_ID_DEFAULT, {touchedPoint});
6532 mDispatcher->notifyMotion(&motionArgs);
6533
6534 mNoInputWindow->assertNoEvents();
6535 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
6536 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
6537 // and therefore should prevent mBottomWindow from receiving touches
6538 mBottomWindow->assertNoEvents();
6539}
6540
6541/**
6542 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
6543 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
6544 */
6545TEST_F(InputDispatcherMultiWindowOcclusionTests,
6546 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006547 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
6548 "Window with input channel and NO_INPUT_CHANNEL",
6549 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006550
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006551 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05006552 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
6553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
6554
6555 PointF touchedPoint = {10, 10};
6556
6557 NotifyMotionArgs motionArgs =
6558 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6559 ADISPLAY_ID_DEFAULT, {touchedPoint});
6560 mDispatcher->notifyMotion(&motionArgs);
6561
6562 mNoInputWindow->assertNoEvents();
6563 mBottomWindow->assertNoEvents();
6564}
6565
Vishnu Nair958da932020-08-21 17:12:37 -07006566class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
6567protected:
6568 std::shared_ptr<FakeApplicationHandle> mApp;
6569 sp<FakeWindowHandle> mWindow;
6570 sp<FakeWindowHandle> mMirror;
6571
6572 virtual void SetUp() override {
6573 InputDispatcherTest::SetUp();
6574 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006575 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6576 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
6577 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07006578 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6579 mWindow->setFocusable(true);
6580 mMirror->setFocusable(true);
6581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6582 }
6583};
6584
6585TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
6586 // Request focus on a mirrored window
6587 setFocusedWindow(mMirror);
6588
6589 // window gets focused
6590 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6592 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006593 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
6594}
6595
6596// A focused & mirrored window remains focused only if the window and its mirror are both
6597// focusable.
6598TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
6599 setFocusedWindow(mMirror);
6600
6601 // window gets focused
6602 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6604 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006605 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6607 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006608 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6609
6610 mMirror->setFocusable(false);
6611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6612
6613 // window loses focus since one of the windows associated with the token in not focusable
6614 mWindow->consumeFocusEvent(false);
6615
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006616 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6617 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006618 mWindow->assertNoEvents();
6619}
6620
6621// A focused & mirrored window remains focused until the window and its mirror both become
6622// invisible.
6623TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
6624 setFocusedWindow(mMirror);
6625
6626 // window gets focused
6627 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6629 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006630 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6632 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006633 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6634
6635 mMirror->setVisible(false);
6636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6637
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6639 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006640 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6642 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006643 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6644
6645 mWindow->setVisible(false);
6646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6647
6648 // window loses focus only after all windows associated with the token become invisible.
6649 mWindow->consumeFocusEvent(false);
6650
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006651 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6652 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006653 mWindow->assertNoEvents();
6654}
6655
6656// A focused & mirrored window remains focused until both windows are removed.
6657TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
6658 setFocusedWindow(mMirror);
6659
6660 // window gets focused
6661 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6663 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006664 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6666 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006667 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6668
6669 // single window is removed but the window token remains focused
6670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
6671
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6673 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006674 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6676 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07006677 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
6678
6679 // Both windows are removed
6680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
6681 mWindow->consumeFocusEvent(false);
6682
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006683 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
6684 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07006685 mWindow->assertNoEvents();
6686}
6687
6688// Focus request can be pending until one window becomes visible.
6689TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
6690 // Request focus on an invisible mirror.
6691 mWindow->setVisible(false);
6692 mMirror->setVisible(false);
6693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6694 setFocusedWindow(mMirror);
6695
6696 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08006697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Harry Cutts33476232023-01-30 19:57:29 +00006698 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, /*repeatCount=*/0, ADISPLAY_ID_DEFAULT,
6699 InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07006700
6701 mMirror->setVisible(true);
6702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
6703
6704 // window gets focused
6705 mWindow->consumeFocusEvent(true);
6706 // window gets the pending key event
6707 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6708}
Prabir Pradhan99987712020-11-10 18:43:05 -08006709
6710class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
6711protected:
6712 std::shared_ptr<FakeApplicationHandle> mApp;
6713 sp<FakeWindowHandle> mWindow;
6714 sp<FakeWindowHandle> mSecondWindow;
6715
6716 void SetUp() override {
6717 InputDispatcherTest::SetUp();
6718 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006719 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006720 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006721 mSecondWindow =
6722 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08006723 mSecondWindow->setFocusable(true);
6724
6725 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6727
6728 setFocusedWindow(mWindow);
6729 mWindow->consumeFocusEvent(true);
6730 }
6731
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006732 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
6733 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006734 mDispatcher->notifyPointerCaptureChanged(&args);
6735 }
6736
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006737 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
6738 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006739 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006740 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
6741 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006742 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006743 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08006744 }
6745};
6746
6747TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
6748 // Ensure that capture cannot be obtained for unfocused windows.
6749 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
6750 mFakePolicy->assertSetPointerCaptureNotCalled();
6751 mSecondWindow->assertNoEvents();
6752
6753 // Ensure that capture can be enabled from the focus window.
6754 requestAndVerifyPointerCapture(mWindow, true);
6755
6756 // Ensure that capture cannot be disabled from a window that does not have capture.
6757 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
6758 mFakePolicy->assertSetPointerCaptureNotCalled();
6759
6760 // Ensure that capture can be disabled from the window with capture.
6761 requestAndVerifyPointerCapture(mWindow, false);
6762}
6763
6764TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006765 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006766
6767 setFocusedWindow(mSecondWindow);
6768
6769 // Ensure that the capture disabled event was sent first.
6770 mWindow->consumeCaptureEvent(false);
6771 mWindow->consumeFocusEvent(false);
6772 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006773 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006774
6775 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006776 notifyPointerCaptureChanged({});
6777 notifyPointerCaptureChanged(request);
6778 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08006779 mWindow->assertNoEvents();
6780 mSecondWindow->assertNoEvents();
6781 mFakePolicy->assertSetPointerCaptureNotCalled();
6782}
6783
6784TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006785 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08006786
6787 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006788 notifyPointerCaptureChanged({});
6789 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08006790
6791 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006792 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08006793 mWindow->consumeCaptureEvent(false);
6794 mWindow->assertNoEvents();
6795}
6796
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006797TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
6798 requestAndVerifyPointerCapture(mWindow, true);
6799
6800 // The first window loses focus.
6801 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006802 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006803 mWindow->consumeCaptureEvent(false);
6804
6805 // Request Pointer Capture from the second window before the notification from InputReader
6806 // arrives.
6807 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006808 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006809
6810 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006811 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006812
6813 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006814 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08006815
6816 mSecondWindow->consumeFocusEvent(true);
6817 mSecondWindow->consumeCaptureEvent(true);
6818}
6819
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006820TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
6821 // App repeatedly enables and disables capture.
6822 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6823 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6824 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6825 mFakePolicy->assertSetPointerCaptureCalled(false);
6826 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6827 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6828
6829 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6830 // first request is now stale, this should do nothing.
6831 notifyPointerCaptureChanged(firstRequest);
6832 mWindow->assertNoEvents();
6833
6834 // InputReader notifies that the second request was enabled.
6835 notifyPointerCaptureChanged(secondRequest);
6836 mWindow->consumeCaptureEvent(true);
6837}
6838
Prabir Pradhan7092e262022-05-03 16:51:09 +00006839TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6840 requestAndVerifyPointerCapture(mWindow, true);
6841
6842 // App toggles pointer capture off and on.
6843 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6844 mFakePolicy->assertSetPointerCaptureCalled(false);
6845
6846 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6847 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6848
6849 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6850 // preceding "disable" request.
6851 notifyPointerCaptureChanged(enableRequest);
6852
6853 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6854 // any notifications.
6855 mWindow->assertNoEvents();
6856}
6857
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006858class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6859protected:
6860 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006861
6862 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6863 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6864
6865 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6866 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6867
6868 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6869 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6870 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6871 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6872 MAXIMUM_OBSCURING_OPACITY);
6873
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006874 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006875 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006876 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006877
6878 sp<FakeWindowHandle> mTouchWindow;
6879
6880 virtual void SetUp() override {
6881 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006882 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006883 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6884 }
6885
6886 virtual void TearDown() override {
6887 InputDispatcherTest::TearDown();
6888 mTouchWindow.clear();
6889 }
6890
chaviw3277faf2021-05-19 16:45:23 -05006891 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6892 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006893 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006894 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006895 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006896 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006897 return window;
6898 }
6899
6900 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6901 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6902 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006903 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006904 // Generate an arbitrary PID based on the UID
6905 window->setOwnerInfo(1777 + (uid % 10000), uid);
6906 return window;
6907 }
6908
6909 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6910 NotifyMotionArgs args =
6911 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6912 ADISPLAY_ID_DEFAULT, points);
6913 mDispatcher->notifyMotion(&args);
6914 }
6915};
6916
6917TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006918 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006919 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006921
6922 touch();
6923
6924 mTouchWindow->assertNoEvents();
6925}
6926
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006927TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006928 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6929 const sp<FakeWindowHandle>& w =
6930 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6931 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6932
6933 touch();
6934
6935 mTouchWindow->assertNoEvents();
6936}
6937
6938TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006939 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6940 const sp<FakeWindowHandle>& w =
6941 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6943
6944 touch();
6945
6946 w->assertNoEvents();
6947}
6948
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006949TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006950 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006952
6953 touch();
6954
6955 mTouchWindow->consumeAnyMotionDown();
6956}
6957
6958TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006959 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006960 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006961 w->setFrame(Rect(0, 0, 50, 50));
6962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006963
6964 touch({PointF{100, 100}});
6965
6966 mTouchWindow->consumeAnyMotionDown();
6967}
6968
6969TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006970 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006971 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006972 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6973
6974 touch();
6975
6976 mTouchWindow->consumeAnyMotionDown();
6977}
6978
6979TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6980 const sp<FakeWindowHandle>& w =
6981 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006983
6984 touch();
6985
6986 mTouchWindow->consumeAnyMotionDown();
6987}
6988
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006989TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6990 const sp<FakeWindowHandle>& w =
6991 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6992 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6993
6994 touch();
6995
6996 w->assertNoEvents();
6997}
6998
6999/**
7000 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
7001 * inside) while letting them pass-through. Note that even though touch passes through the occluding
7002 * window, the occluding window will still receive ACTION_OUTSIDE event.
7003 */
7004TEST_F(InputDispatcherUntrustedTouchesTest,
7005 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
7006 const sp<FakeWindowHandle>& w =
7007 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007008 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7010
7011 touch();
7012
7013 w->consumeMotionOutside();
7014}
7015
7016TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
7017 const sp<FakeWindowHandle>& w =
7018 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007019 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7021
7022 touch();
7023
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007024 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00007025}
7026
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007027TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007028 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007029 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7030 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7032
7033 touch();
7034
7035 mTouchWindow->consumeAnyMotionDown();
7036}
7037
7038TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
7039 const sp<FakeWindowHandle>& w =
7040 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7041 MAXIMUM_OBSCURING_OPACITY);
7042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007043
7044 touch();
7045
7046 mTouchWindow->consumeAnyMotionDown();
7047}
7048
7049TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007050 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007051 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7052 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7054
7055 touch();
7056
7057 mTouchWindow->assertNoEvents();
7058}
7059
7060TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
7061 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
7062 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007063 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7064 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007065 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007066 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7067 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7069
7070 touch();
7071
7072 mTouchWindow->assertNoEvents();
7073}
7074
7075TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
7076 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
7077 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007078 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
7079 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007080 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007081 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
7082 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7084
7085 touch();
7086
7087 mTouchWindow->consumeAnyMotionDown();
7088}
7089
7090TEST_F(InputDispatcherUntrustedTouchesTest,
7091 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
7092 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007093 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7094 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007095 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007096 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7097 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7099
7100 touch();
7101
7102 mTouchWindow->consumeAnyMotionDown();
7103}
7104
7105TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
7106 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007107 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7108 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007109 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007110 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7111 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00007112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00007113
7114 touch();
7115
7116 mTouchWindow->assertNoEvents();
7117}
7118
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007119TEST_F(InputDispatcherUntrustedTouchesTest,
7120 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
7121 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007122 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7123 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007124 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007125 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7126 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7128
7129 touch();
7130
7131 mTouchWindow->assertNoEvents();
7132}
7133
7134TEST_F(InputDispatcherUntrustedTouchesTest,
7135 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
7136 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007137 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7138 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007139 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007140 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7141 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007142 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
7143
7144 touch();
7145
7146 mTouchWindow->consumeAnyMotionDown();
7147}
7148
7149TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
7150 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007151 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
7152 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00007153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7154
7155 touch();
7156
7157 mTouchWindow->consumeAnyMotionDown();
7158}
7159
7160TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
7161 const sp<FakeWindowHandle>& w =
7162 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
7163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7164
7165 touch();
7166
7167 mTouchWindow->consumeAnyMotionDown();
7168}
7169
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007170TEST_F(InputDispatcherUntrustedTouchesTest,
7171 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
7172 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7173 const sp<FakeWindowHandle>& w =
7174 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
7175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7176
7177 touch();
7178
7179 mTouchWindow->assertNoEvents();
7180}
7181
7182TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
7183 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
7184 const sp<FakeWindowHandle>& w =
7185 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
7186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7187
7188 touch();
7189
7190 mTouchWindow->consumeAnyMotionDown();
7191}
7192
7193TEST_F(InputDispatcherUntrustedTouchesTest,
7194 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
7195 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
7196 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00007197 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7198 OPACITY_ABOVE_THRESHOLD);
7199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7200
7201 touch();
7202
7203 mTouchWindow->consumeAnyMotionDown();
7204}
7205
7206TEST_F(InputDispatcherUntrustedTouchesTest,
7207 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
7208 const sp<FakeWindowHandle>& w1 =
7209 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7210 OPACITY_BELOW_THRESHOLD);
7211 const sp<FakeWindowHandle>& w2 =
7212 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
7213 OPACITY_BELOW_THRESHOLD);
7214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
7215
7216 touch();
7217
7218 mTouchWindow->assertNoEvents();
7219}
7220
7221/**
7222 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
7223 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
7224 * (which alone would result in allowing touches) does not affect the blocking behavior.
7225 */
7226TEST_F(InputDispatcherUntrustedTouchesTest,
7227 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
7228 const sp<FakeWindowHandle>& wB =
7229 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
7230 OPACITY_BELOW_THRESHOLD);
7231 const sp<FakeWindowHandle>& wC =
7232 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
7233 OPACITY_BELOW_THRESHOLD);
7234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
7235
7236 touch();
7237
7238 mTouchWindow->assertNoEvents();
7239}
7240
7241/**
7242 * This test is testing that a window from a different UID but with same application token doesn't
7243 * block the touch. Apps can share the application token for close UI collaboration for example.
7244 */
7245TEST_F(InputDispatcherUntrustedTouchesTest,
7246 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
7247 const sp<FakeWindowHandle>& w =
7248 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
7249 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00007250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
7251
7252 touch();
7253
7254 mTouchWindow->consumeAnyMotionDown();
7255}
7256
arthurhungb89ccb02020-12-30 16:19:01 +08007257class InputDispatcherDragTests : public InputDispatcherTest {
7258protected:
7259 std::shared_ptr<FakeApplicationHandle> mApp;
7260 sp<FakeWindowHandle> mWindow;
7261 sp<FakeWindowHandle> mSecondWindow;
7262 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007263 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007264 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
7265 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08007266
7267 void SetUp() override {
7268 InputDispatcherTest::SetUp();
7269 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007270 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007271 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007272
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007273 mSecondWindow =
7274 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08007275 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08007276
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007277 mSpyWindow =
7278 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007279 mSpyWindow->setSpy(true);
7280 mSpyWindow->setTrustedOverlay(true);
7281 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
7282
arthurhungb89ccb02020-12-30 16:19:01 +08007283 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007285 }
7286
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007287 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
7288 switch (fromSource) {
7289 case AINPUT_SOURCE_TOUCHSCREEN:
7290 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7291 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
7292 ADISPLAY_ID_DEFAULT, {50, 50}))
7293 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7294 break;
7295 case AINPUT_SOURCE_STYLUS:
7296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7297 injectMotionEvent(
7298 mDispatcher,
7299 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7300 AINPUT_SOURCE_STYLUS)
7301 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7302 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7303 .x(50)
7304 .y(50))
7305 .build()));
7306 break;
7307 case AINPUT_SOURCE_MOUSE:
7308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7309 injectMotionEvent(
7310 mDispatcher,
7311 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
7312 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7313 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7314 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7315 .x(50)
7316 .y(50))
7317 .build()));
7318 break;
7319 default:
7320 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
7321 }
arthurhungb89ccb02020-12-30 16:19:01 +08007322
7323 // Window should receive motion event.
7324 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007325 // Spy window should also receive motion event
7326 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00007327 }
7328
7329 // Start performing drag, we will create a drag window and transfer touch to it.
7330 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
7331 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007332 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00007333 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007334 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00007335 }
arthurhungb89ccb02020-12-30 16:19:01 +08007336
7337 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007338 mDragWindow =
7339 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007340 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08007341 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007342 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08007343
7344 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00007345 bool transferred =
7346 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
Harry Cutts33476232023-01-30 19:57:29 +00007347 /*isDragDrop=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00007348 if (transferred) {
7349 mWindow->consumeMotionCancel();
7350 mDragWindow->consumeMotionDown();
7351 }
7352 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08007353 }
7354};
7355
7356TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007357 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08007358
7359 // Move on window.
7360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7361 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7362 ADISPLAY_ID_DEFAULT, {50, 50}))
7363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7364 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7365 mWindow->consumeDragEvent(false, 50, 50);
7366 mSecondWindow->assertNoEvents();
7367
7368 // Move to another window.
7369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7370 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7371 ADISPLAY_ID_DEFAULT, {150, 50}))
7372 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7373 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7374 mWindow->consumeDragEvent(true, 150, 50);
7375 mSecondWindow->consumeDragEvent(false, 50, 50);
7376
7377 // Move back to original window.
7378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7379 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7380 ADISPLAY_ID_DEFAULT, {50, 50}))
7381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7382 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7383 mWindow->consumeDragEvent(false, 50, 50);
7384 mSecondWindow->consumeDragEvent(true, -50, 50);
7385
7386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7387 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
7388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7389 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7390 mWindow->assertNoEvents();
7391 mSecondWindow->assertNoEvents();
7392}
7393
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007394TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007395 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007396
7397 // No cancel event after drag start
7398 mSpyWindow->assertNoEvents();
7399
7400 const MotionEvent secondFingerDownEvent =
7401 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7402 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007403 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7404 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00007405 .build();
7406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7407 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7408 InputEventInjectionSync::WAIT_FOR_RESULT))
7409 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7410
7411 // Receives cancel for first pointer after next pointer down
7412 mSpyWindow->consumeMotionCancel();
7413 mSpyWindow->consumeMotionDown();
7414
7415 mSpyWindow->assertNoEvents();
7416}
7417
arthurhungf452d0b2021-01-06 00:19:52 +08007418TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007419 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08007420
7421 // Move on window.
7422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7423 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7424 ADISPLAY_ID_DEFAULT, {50, 50}))
7425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7426 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7427 mWindow->consumeDragEvent(false, 50, 50);
7428 mSecondWindow->assertNoEvents();
7429
7430 // Move to another window.
7431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7432 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7433 ADISPLAY_ID_DEFAULT, {150, 50}))
7434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7435 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7436 mWindow->consumeDragEvent(true, 150, 50);
7437 mSecondWindow->consumeDragEvent(false, 50, 50);
7438
7439 // drop to another window.
7440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7441 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7442 {150, 50}))
7443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7444 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7445 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7446 mWindow->assertNoEvents();
7447 mSecondWindow->assertNoEvents();
7448}
7449
arthurhung6d4bed92021-03-17 11:59:33 +08007450TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007451 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08007452
7453 // Move on window and keep button pressed.
7454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7455 injectMotionEvent(mDispatcher,
7456 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7457 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
7458 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7459 .x(50)
7460 .y(50))
7461 .build()))
7462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7463 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7464 mWindow->consumeDragEvent(false, 50, 50);
7465 mSecondWindow->assertNoEvents();
7466
7467 // Move to another window and release button, expect to drop item.
7468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7469 injectMotionEvent(mDispatcher,
7470 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
7471 .buttonState(0)
7472 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7473 .x(150)
7474 .y(50))
7475 .build()))
7476 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7477 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7478 mWindow->assertNoEvents();
7479 mSecondWindow->assertNoEvents();
7480 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7481
7482 // nothing to the window.
7483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7484 injectMotionEvent(mDispatcher,
7485 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
7486 .buttonState(0)
7487 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
7488 .x(150)
7489 .y(50))
7490 .build()))
7491 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7492 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7493 mWindow->assertNoEvents();
7494 mSecondWindow->assertNoEvents();
7495}
7496
Arthur Hung54745652022-04-20 07:17:41 +00007497TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007498 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08007499
7500 // Set second window invisible.
7501 mSecondWindow->setVisible(false);
7502 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
7503
7504 // Move on window.
7505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7506 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7507 ADISPLAY_ID_DEFAULT, {50, 50}))
7508 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7509 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7510 mWindow->consumeDragEvent(false, 50, 50);
7511 mSecondWindow->assertNoEvents();
7512
7513 // Move to another window.
7514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7515 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7516 ADISPLAY_ID_DEFAULT, {150, 50}))
7517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7518 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7519 mWindow->consumeDragEvent(true, 150, 50);
7520 mSecondWindow->assertNoEvents();
7521
7522 // drop to another window.
7523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7524 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7525 {150, 50}))
7526 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7527 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7528 mFakePolicy->assertDropTargetEquals(nullptr);
7529 mWindow->assertNoEvents();
7530 mSecondWindow->assertNoEvents();
7531}
7532
Arthur Hung54745652022-04-20 07:17:41 +00007533TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007534 // Ensure window could track pointerIds if it didn't support split touch.
7535 mWindow->setPreventSplitting(true);
7536
Arthur Hung54745652022-04-20 07:17:41 +00007537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7538 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7539 {50, 50}))
7540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7541 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7542
7543 const MotionEvent secondFingerDownEvent =
7544 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7545 .displayId(ADISPLAY_ID_DEFAULT)
7546 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007547 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7548 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007549 .build();
7550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7551 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7552 InputEventInjectionSync::WAIT_FOR_RESULT))
7553 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00007554 mWindow->consumeMotionPointerDown(/*pointerIndex=*/1);
Arthur Hung54745652022-04-20 07:17:41 +00007555
7556 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007557 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007558}
7559
7560TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
7561 // First down on second window.
7562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7564 {150, 50}))
7565 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7566
7567 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7568
7569 // Second down on first window.
7570 const MotionEvent secondFingerDownEvent =
7571 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7572 .displayId(ADISPLAY_ID_DEFAULT)
7573 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007574 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7575 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007576 .build();
7577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7578 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7579 InputEventInjectionSync::WAIT_FOR_RESULT))
7580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7581 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7582
7583 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007584 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00007585
7586 // Move on window.
7587 const MotionEvent secondFingerMoveEvent =
7588 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
7589 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007590 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7591 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007592 .build();
7593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7594 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
7595 InputEventInjectionSync::WAIT_FOR_RESULT));
7596 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7597 mWindow->consumeDragEvent(false, 50, 50);
7598 mSecondWindow->consumeMotionMove();
7599
7600 // Release the drag pointer should perform drop.
7601 const MotionEvent secondFingerUpEvent =
7602 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
7603 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00007604 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7605 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Arthur Hung54745652022-04-20 07:17:41 +00007606 .build();
7607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7608 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
7609 InputEventInjectionSync::WAIT_FOR_RESULT));
7610 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7611 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
7612 mWindow->assertNoEvents();
7613 mSecondWindow->consumeMotionMove();
7614}
7615
Arthur Hung3915c1f2022-05-31 07:17:17 +00007616TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007617 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00007618
7619 // Update window of second display.
7620 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007621 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00007622 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7623
7624 // Let second display has a touch state.
7625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7626 injectMotionEvent(mDispatcher,
7627 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
7628 AINPUT_SOURCE_TOUCHSCREEN)
7629 .displayId(SECOND_DISPLAY_ID)
7630 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7631 .x(100)
7632 .y(100))
7633 .build()));
7634 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
Harry Cutts33476232023-01-30 19:57:29 +00007635 SECOND_DISPLAY_ID, /*expectedFlag=*/0);
Arthur Hung3915c1f2022-05-31 07:17:17 +00007636 // Update window again.
7637 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
7638
7639 // Move on window.
7640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7641 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7642 ADISPLAY_ID_DEFAULT, {50, 50}))
7643 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7644 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7645 mWindow->consumeDragEvent(false, 50, 50);
7646 mSecondWindow->assertNoEvents();
7647
7648 // Move to another window.
7649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7650 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7651 ADISPLAY_ID_DEFAULT, {150, 50}))
7652 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7653 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7654 mWindow->consumeDragEvent(true, 150, 50);
7655 mSecondWindow->consumeDragEvent(false, 50, 50);
7656
7657 // drop to another window.
7658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7659 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7660 {150, 50}))
7661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7662 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7663 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7664 mWindow->assertNoEvents();
7665 mSecondWindow->assertNoEvents();
7666}
7667
Arthur Hungb75c2aa2022-07-15 09:35:36 +00007668TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
7669 startDrag(true, AINPUT_SOURCE_MOUSE);
7670 // Move on window.
7671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7672 injectMotionEvent(mDispatcher,
7673 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7674 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7675 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7676 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7677 .x(50)
7678 .y(50))
7679 .build()))
7680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7681 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7682 mWindow->consumeDragEvent(false, 50, 50);
7683 mSecondWindow->assertNoEvents();
7684
7685 // Move to another window.
7686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7687 injectMotionEvent(mDispatcher,
7688 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
7689 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
7690 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7691 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7692 .x(150)
7693 .y(50))
7694 .build()))
7695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7696 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
7697 mWindow->consumeDragEvent(true, 150, 50);
7698 mSecondWindow->consumeDragEvent(false, 50, 50);
7699
7700 // drop to another window.
7701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7702 injectMotionEvent(mDispatcher,
7703 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
7704 .buttonState(0)
7705 .pointer(PointerBuilder(MOUSE_POINTER_ID,
7706 AMOTION_EVENT_TOOL_TYPE_MOUSE)
7707 .x(150)
7708 .y(50))
7709 .build()))
7710 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7711 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7712 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
7713 mWindow->assertNoEvents();
7714 mSecondWindow->assertNoEvents();
7715}
7716
Vishnu Nair062a8672021-09-03 16:07:44 -07007717class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
7718
7719TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
7720 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007721 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7722 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007723 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007724 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7725 window->setFocusable(true);
7726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7727 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007728 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007729
7730 // With the flag set, window should not get any input
7731 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7732 mDispatcher->notifyKey(&keyArgs);
7733 window->assertNoEvents();
7734
7735 NotifyMotionArgs motionArgs =
7736 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7737 ADISPLAY_ID_DEFAULT);
7738 mDispatcher->notifyMotion(&motionArgs);
7739 window->assertNoEvents();
7740
7741 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007742 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7744
7745 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7746 mDispatcher->notifyKey(&keyArgs);
7747 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7748
7749 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7750 ADISPLAY_ID_DEFAULT);
7751 mDispatcher->notifyMotion(&motionArgs);
7752 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7753 window->assertNoEvents();
7754}
7755
7756TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
7757 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7758 std::make_shared<FakeApplicationHandle>();
7759 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007760 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7761 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007762 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7763 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007764 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007765 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007766 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7767 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007768 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007769 window->setOwnerInfo(222, 222);
7770 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7771 window->setFocusable(true);
7772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7773 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007774 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007775
7776 // With the flag set, window should not get any input
7777 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7778 mDispatcher->notifyKey(&keyArgs);
7779 window->assertNoEvents();
7780
7781 NotifyMotionArgs motionArgs =
7782 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7783 ADISPLAY_ID_DEFAULT);
7784 mDispatcher->notifyMotion(&motionArgs);
7785 window->assertNoEvents();
7786
7787 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007788 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7790
7791 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7792 mDispatcher->notifyKey(&keyArgs);
7793 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7794
7795 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7796 ADISPLAY_ID_DEFAULT);
7797 mDispatcher->notifyMotion(&motionArgs);
7798 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
7799 window->assertNoEvents();
7800}
7801
7802TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
7803 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
7804 std::make_shared<FakeApplicationHandle>();
7805 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007806 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
7807 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07007808 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
7809 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007810 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07007811 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007812 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
7813 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007814 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007815 window->setOwnerInfo(222, 222);
7816 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7817 window->setFocusable(true);
7818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
7819 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00007820 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Vishnu Nair062a8672021-09-03 16:07:44 -07007821
7822 // With the flag set, window should not get any input
7823 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7824 mDispatcher->notifyKey(&keyArgs);
7825 window->assertNoEvents();
7826
7827 NotifyMotionArgs motionArgs =
7828 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7829 ADISPLAY_ID_DEFAULT);
7830 mDispatcher->notifyMotion(&motionArgs);
7831 window->assertNoEvents();
7832
7833 // When the window is no longer obscured because it went on top, it should get input
7834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7835
7836 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7837 mDispatcher->notifyKey(&keyArgs);
7838 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7839
7840 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7841 ADISPLAY_ID_DEFAULT);
7842 mDispatcher->notifyMotion(&motionArgs);
7843 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7844 window->assertNoEvents();
7845}
7846
Antonio Kantekf16f2832021-09-28 04:39:20 +00007847class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7848protected:
7849 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007850 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007851 sp<FakeWindowHandle> mWindow;
7852 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007853 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007854
7855 void SetUp() override {
7856 InputDispatcherTest::SetUp();
7857
7858 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007859 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007860 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007861 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007862 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007863 mSecondWindow =
7864 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007865 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007866 mThirdWindow =
7867 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7868 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7869 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007870
7871 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7873 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7874 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007875 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007876
Antonio Kantek15beb512022-06-13 22:35:41 +00007877 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007878 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00007879 WINDOW_UID, /*hasPermission=*/true, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007880 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7881 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007882 mThirdWindow->assertNoEvents();
7883 }
7884
7885 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7886 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
Harry Cutts33476232023-01-30 19:57:29 +00007887 SECONDARY_WINDOW_UID, /*hasPermission=*/true,
Antonio Kantek15beb512022-06-13 22:35:41 +00007888 SECOND_DISPLAY_ID)) {
7889 mWindow->assertNoEvents();
7890 mSecondWindow->assertNoEvents();
7891 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007892 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007893 }
7894
Antonio Kantek15beb512022-06-13 22:35:41 +00007895 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7896 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007897 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7898 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007899 mWindow->consumeTouchModeEvent(inTouchMode);
7900 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007901 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007902 }
7903};
7904
Antonio Kantek26defcf2022-02-08 01:12:27 +00007905TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007906 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007907 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7908 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007909 /* hasPermission=*/false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007910}
7911
Antonio Kantek26defcf2022-02-08 01:12:27 +00007912TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7913 const WindowInfo& windowInfo = *mWindow->getInfo();
7914 int32_t ownerPid = windowInfo.ownerPid;
7915 int32_t ownerUid = windowInfo.ownerUid;
7916 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7917 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00007918 ownerUid, /*hasPermission=*/false,
Antonio Kanteka042c022022-07-06 16:51:07 -07007919 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007920 mWindow->assertNoEvents();
7921 mSecondWindow->assertNoEvents();
7922}
7923
7924TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7925 const WindowInfo& windowInfo = *mWindow->getInfo();
7926 int32_t ownerPid = windowInfo.ownerPid;
7927 int32_t ownerUid = windowInfo.ownerUid;
7928 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007929 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
Harry Cutts33476232023-01-30 19:57:29 +00007930 ownerUid, /*hasPermission=*/true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007931}
7932
Antonio Kantekf16f2832021-09-28 04:39:20 +00007933TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007934 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007935 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7936 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007937 /*hasPermission=*/true, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007938 mWindow->assertNoEvents();
7939 mSecondWindow->assertNoEvents();
7940}
7941
Antonio Kantek15beb512022-06-13 22:35:41 +00007942TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7943 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7944 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7945 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007946 /*hasPermission=*/true, SECOND_DISPLAY_ID));
Antonio Kantek15beb512022-06-13 22:35:41 +00007947 mWindow->assertNoEvents();
7948 mSecondWindow->assertNoEvents();
7949 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7950}
7951
Antonio Kantek48710e42022-03-24 14:19:30 -07007952TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7953 // Interact with the window first.
7954 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7955 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7956 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7957
7958 // Then remove focus.
7959 mWindow->setFocusable(false);
7960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7961
7962 // Assert that caller can switch touch mode by owning one of the last interacted window.
7963 const WindowInfo& windowInfo = *mWindow->getInfo();
7964 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7965 windowInfo.ownerPid, windowInfo.ownerUid,
Harry Cutts33476232023-01-30 19:57:29 +00007966 /*hasPermission=*/false, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007967}
7968
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007969class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7970public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007971 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007972 std::shared_ptr<FakeApplicationHandle> application =
7973 std::make_shared<FakeApplicationHandle>();
7974 std::string name = "Fake Spy ";
7975 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007976 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7977 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007978 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007979 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007980 return spy;
7981 }
7982
7983 sp<FakeWindowHandle> createForeground() {
7984 std::shared_ptr<FakeApplicationHandle> application =
7985 std::make_shared<FakeApplicationHandle>();
7986 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007987 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7988 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007989 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007990 return window;
7991 }
7992
7993private:
7994 int mSpyCount{0};
7995};
7996
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007997using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007998/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007999 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
8000 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008001TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
8002 ScopedSilentDeath _silentDeath;
8003
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008004 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08008005 spy->setTrustedOverlay(false);
8006 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
8007 ".* not a trusted overlay");
8008}
8009
8010/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008011 * Input injection into a display with a spy window but no foreground windows should succeed.
8012 */
8013TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008014 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008015 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
8016
8017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8018 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8020 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8021}
8022
8023/**
8024 * Verify the order in which different input windows receive events. The touched foreground window
8025 * (if there is one) should always receive the event first. When there are multiple spy windows, the
8026 * spy windows will receive the event according to their Z-order, where the top-most spy window will
8027 * receive events before ones belows it.
8028 *
8029 * Here, we set up a scenario with four windows in the following Z order from the top:
8030 * spy1, spy2, window, spy3.
8031 * We then inject an event and verify that the foreground "window" receives it first, followed by
8032 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
8033 * window.
8034 */
8035TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
8036 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008037 auto spy1 = createSpy();
8038 auto spy2 = createSpy();
8039 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
8041 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
8042 const size_t numChannels = channels.size();
8043
Michael Wright8e9a8562022-02-09 13:44:29 +00008044 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008045 if (!epollFd.ok()) {
8046 FAIL() << "Failed to create epoll fd";
8047 }
8048
8049 for (size_t i = 0; i < numChannels; i++) {
8050 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
8051 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
8052 FAIL() << "Failed to add fd to epoll";
8053 }
8054 }
8055
8056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8059
8060 std::vector<size_t> eventOrder;
8061 std::vector<struct epoll_event> events(numChannels);
8062 for (;;) {
8063 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
8064 (100ms).count());
8065 if (nFds < 0) {
8066 FAIL() << "Failed to call epoll_wait";
8067 }
8068 if (nFds == 0) {
8069 break; // epoll_wait timed out
8070 }
8071 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07008072 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07008073 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008074 channels[i]->consumeMotionDown();
8075 }
8076 }
8077
8078 // Verify the order in which the events were received.
8079 EXPECT_EQ(3u, eventOrder.size());
8080 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
8081 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
8082 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
8083}
8084
8085/**
8086 * A spy window using the NOT_TOUCHABLE flag does not receive events.
8087 */
8088TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
8089 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008090 auto spy = createSpy();
8091 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8093
8094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8095 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8097 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8098 spy->assertNoEvents();
8099}
8100
8101/**
8102 * A spy window will only receive gestures that originate within its touchable region. Gestures that
8103 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
8104 * to the window.
8105 */
8106TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
8107 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008108 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008109 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
8110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8111
8112 // Inject an event outside the spy window's touchable region.
8113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8114 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8115 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8116 window->consumeMotionDown();
8117 spy->assertNoEvents();
8118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8119 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8120 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8121 window->consumeMotionUp();
8122 spy->assertNoEvents();
8123
8124 // Inject an event inside the spy window's touchable region.
8125 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8126 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8127 {5, 10}))
8128 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8129 window->consumeMotionDown();
8130 spy->consumeMotionDown();
8131}
8132
8133/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008134 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008135 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008136 */
8137TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
8138 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008139 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008140 auto spy = createSpy();
8141 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008142 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008143 spy->setFrame(Rect{0, 0, 20, 20});
8144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8145
8146 // Inject an event outside the spy window's frame and touchable region.
8147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008148 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8149 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008150 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8151 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08008152 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008153}
8154
8155/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008156 * Even when a spy window spans over multiple foreground windows, the spy should receive all
8157 * pointers that are down within its bounds.
8158 */
8159TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
8160 auto windowLeft = createForeground();
8161 windowLeft->setFrame({0, 0, 100, 200});
8162 auto windowRight = createForeground();
8163 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008164 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008165 spy->setFrame({0, 0, 200, 200});
8166 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
8167
8168 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8169 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8170 {50, 50}))
8171 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8172 windowLeft->consumeMotionDown();
8173 spy->consumeMotionDown();
8174
8175 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008176 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008177 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008178 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8179 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008180 .build();
8181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8182 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8183 InputEventInjectionSync::WAIT_FOR_RESULT))
8184 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8185 windowRight->consumeMotionDown();
Harry Cutts33476232023-01-30 19:57:29 +00008186 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008187}
8188
8189/**
8190 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
8191 * the spy should receive the second pointer with ACTION_DOWN.
8192 */
8193TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
8194 auto window = createForeground();
8195 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008196 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008197 spyRight->setFrame({100, 0, 200, 200});
8198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
8199
8200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8202 {50, 50}))
8203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8204 window->consumeMotionDown();
8205 spyRight->assertNoEvents();
8206
8207 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008208 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008209 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008210 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8211 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008212 .build();
8213 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8214 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8215 InputEventInjectionSync::WAIT_FOR_RESULT))
8216 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Harry Cutts33476232023-01-30 19:57:29 +00008217 window->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08008218 spyRight->consumeMotionDown();
8219}
8220
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008221/**
8222 * The spy window should not be able to affect whether or not touches are split. Only the foreground
8223 * windows should be allowed to control split touch.
8224 */
8225TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008226 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008227 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008228 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08008229 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008230
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008231 auto window = createForeground();
8232 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008233
8234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8235
8236 // First finger down, no window touched.
8237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8238 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8239 {100, 200}))
8240 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8241 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8242 window->assertNoEvents();
8243
8244 // Second finger down on window, the window should receive touch down.
8245 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08008246 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008247 .displayId(ADISPLAY_ID_DEFAULT)
8248 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008249 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8250 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008251 .build();
8252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8253 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8254 InputEventInjectionSync::WAIT_FOR_RESULT))
8255 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8256
8257 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Harry Cutts33476232023-01-30 19:57:29 +00008258 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008259}
8260
8261/**
8262 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
8263 * do not receive key events.
8264 */
8265TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008266 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08008267 spy->setFocusable(false);
8268
8269 auto window = createForeground();
8270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8271 setFocusedWindow(window);
8272 window->consumeFocusEvent(true);
8273
8274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
8275 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8276 window->consumeKeyDown(ADISPLAY_ID_NONE);
8277
8278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
8279 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
8280 window->consumeKeyUp(ADISPLAY_ID_NONE);
8281
8282 spy->assertNoEvents();
8283}
8284
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008285using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
8286
8287/**
8288 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
8289 * are currently sent to any other windows - including other spy windows - will also be cancelled.
8290 */
8291TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
8292 auto window = createForeground();
8293 auto spy1 = createSpy();
8294 auto spy2 = createSpy();
8295 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
8296
8297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8299 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8300 window->consumeMotionDown();
8301 spy1->consumeMotionDown();
8302 spy2->consumeMotionDown();
8303
8304 // Pilfer pointers from the second spy window.
8305 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
8306 spy2->assertNoEvents();
8307 spy1->consumeMotionCancel();
8308 window->consumeMotionCancel();
8309
8310 // The rest of the gesture should only be sent to the second spy window.
8311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8312 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
8313 ADISPLAY_ID_DEFAULT))
8314 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8315 spy2->consumeMotionMove();
8316 spy1->assertNoEvents();
8317 window->assertNoEvents();
8318}
8319
8320/**
8321 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
8322 * in the middle of the gesture.
8323 */
8324TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
8325 auto window = createForeground();
8326 auto spy = createSpy();
8327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8328
8329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8330 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8331 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8332 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8333 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
8334
8335 window->releaseChannel();
8336
8337 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8338
8339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8340 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
8341 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8342 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
8343}
8344
8345/**
8346 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
8347 * the spy, but not to any other windows.
8348 */
8349TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
8350 auto spy = createSpy();
8351 auto window = createForeground();
8352
8353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8354
8355 // First finger down on the window and the spy.
8356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8357 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8358 {100, 200}))
8359 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8360 spy->consumeMotionDown();
8361 window->consumeMotionDown();
8362
8363 // Spy window pilfers the pointers.
8364 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8365 window->consumeMotionCancel();
8366
8367 // Second finger down on the window and spy, but the window should not receive the pointer down.
8368 const MotionEvent secondFingerDownEvent =
8369 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8370 .displayId(ADISPLAY_ID_DEFAULT)
8371 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008372 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8373 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008374 .build();
8375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8376 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8377 InputEventInjectionSync::WAIT_FOR_RESULT))
8378 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8379
Harry Cutts33476232023-01-30 19:57:29 +00008380 spy->consumeMotionPointerDown(/*pointerIndex=*/1);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008381
8382 // Third finger goes down outside all windows, so injection should fail.
8383 const MotionEvent thirdFingerDownEvent =
8384 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8385 .displayId(ADISPLAY_ID_DEFAULT)
8386 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008387 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(100).y(200))
8388 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
8389 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008390 .build();
8391 ASSERT_EQ(InputEventInjectionResult::FAILED,
8392 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8393 InputEventInjectionSync::WAIT_FOR_RESULT))
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08008394 << "Inject motion event should return InputEventInjectionResult::FAILED";
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008395
8396 spy->assertNoEvents();
8397 window->assertNoEvents();
8398}
8399
8400/**
8401 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
8402 */
8403TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
8404 auto spy = createSpy();
8405 spy->setFrame(Rect(0, 0, 100, 100));
8406 auto window = createForeground();
8407 window->setFrame(Rect(0, 0, 200, 200));
8408
8409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8410
8411 // First finger down on the window only
8412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8413 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8414 {150, 150}))
8415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8416 window->consumeMotionDown();
8417
8418 // Second finger down on the spy and window
8419 const MotionEvent secondFingerDownEvent =
8420 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8421 .displayId(ADISPLAY_ID_DEFAULT)
8422 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008423 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8424 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008425 .build();
8426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8427 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8428 InputEventInjectionSync::WAIT_FOR_RESULT))
8429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8430 spy->consumeMotionDown();
8431 window->consumeMotionPointerDown(1);
8432
8433 // Third finger down on the spy and window
8434 const MotionEvent thirdFingerDownEvent =
8435 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8436 .displayId(ADISPLAY_ID_DEFAULT)
8437 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008438 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
8439 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8440 .pointer(PointerBuilder(/*id=*/2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008441 .build();
8442 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8443 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
8444 InputEventInjectionSync::WAIT_FOR_RESULT))
8445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8446 spy->consumeMotionPointerDown(1);
8447 window->consumeMotionPointerDown(2);
8448
8449 // Spy window pilfers the pointers.
8450 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8451 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8452 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
8453
8454 spy->assertNoEvents();
8455 window->assertNoEvents();
8456}
8457
8458/**
8459 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
8460 * other windows should be canceled. If this results in the cancellation of all pointers for some
8461 * window, then that window should receive ACTION_CANCEL.
8462 */
8463TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
8464 auto spy = createSpy();
8465 spy->setFrame(Rect(0, 0, 100, 100));
8466 auto window = createForeground();
8467 window->setFrame(Rect(0, 0, 200, 200));
8468
8469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8470
8471 // First finger down on both spy and window
8472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8474 {10, 10}))
8475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8476 window->consumeMotionDown();
8477 spy->consumeMotionDown();
8478
8479 // Second finger down on the spy and window
8480 const MotionEvent secondFingerDownEvent =
8481 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8482 .displayId(ADISPLAY_ID_DEFAULT)
8483 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008484 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8485 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008486 .build();
8487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8488 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8489 InputEventInjectionSync::WAIT_FOR_RESULT))
8490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8491 spy->consumeMotionPointerDown(1);
8492 window->consumeMotionPointerDown(1);
8493
8494 // Spy window pilfers the pointers.
8495 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8496 window->consumeMotionCancel();
8497
8498 spy->assertNoEvents();
8499 window->assertNoEvents();
8500}
8501
8502/**
8503 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
8504 * be sent to other windows
8505 */
8506TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
8507 auto spy = createSpy();
8508 spy->setFrame(Rect(0, 0, 100, 100));
8509 auto window = createForeground();
8510 window->setFrame(Rect(0, 0, 200, 200));
8511
8512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8513
8514 // First finger down on both window and spy
8515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
8517 {10, 10}))
8518 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8519 window->consumeMotionDown();
8520 spy->consumeMotionDown();
8521
8522 // Spy window pilfers the pointers.
8523 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
8524 window->consumeMotionCancel();
8525
8526 // Second finger down on the window only
8527 const MotionEvent secondFingerDownEvent =
8528 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
8529 .displayId(ADISPLAY_ID_DEFAULT)
8530 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
Harry Cutts33476232023-01-30 19:57:29 +00008531 .pointer(PointerBuilder(/*id=*/0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
8532 .pointer(PointerBuilder(/*id=*/1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(150))
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00008533 .build();
8534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
8535 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
8536 InputEventInjectionSync::WAIT_FOR_RESULT))
8537 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
8538 window->consumeMotionDown();
8539 window->assertNoEvents();
8540
8541 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
8542 spy->consumeMotionMove();
8543 spy->assertNoEvents();
8544}
8545
Prabir Pradhand65552b2021-10-07 11:23:50 -07008546class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
8547public:
8548 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
8549 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8550 std::make_shared<FakeApplicationHandle>();
8551 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008552 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
8553 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008554 overlay->setFocusable(false);
8555 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08008556 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008557 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008558 overlay->setTrustedOverlay(true);
8559
8560 std::shared_ptr<FakeApplicationHandle> application =
8561 std::make_shared<FakeApplicationHandle>();
8562 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008563 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
8564 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008565 window->setFocusable(true);
8566 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008567
8568 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
8569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8570 setFocusedWindow(window);
Harry Cutts33476232023-01-30 19:57:29 +00008571 window->consumeFocusEvent(/*hasFocus=*/true, /*inTouchMode=*/true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008572 return {std::move(overlay), std::move(window)};
8573 }
8574
8575 void sendFingerEvent(int32_t action) {
8576 NotifyMotionArgs motionArgs =
8577 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8578 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
8579 mDispatcher->notifyMotion(&motionArgs);
8580 }
8581
8582 void sendStylusEvent(int32_t action) {
8583 NotifyMotionArgs motionArgs =
8584 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
8585 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
8586 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
8587 mDispatcher->notifyMotion(&motionArgs);
8588 }
8589};
8590
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08008591using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
8592
8593TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
8594 ScopedSilentDeath _silentDeath;
8595
Prabir Pradhand65552b2021-10-07 11:23:50 -07008596 auto [overlay, window] = setupStylusOverlayScenario();
8597 overlay->setTrustedOverlay(false);
8598 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
8599 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
8600 ".* not a trusted overlay");
8601}
8602
8603TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
8604 auto [overlay, window] = setupStylusOverlayScenario();
8605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8606
8607 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8608 overlay->consumeMotionDown();
8609 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8610 overlay->consumeMotionUp();
8611
8612 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8613 window->consumeMotionDown();
8614 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8615 window->consumeMotionUp();
8616
8617 overlay->assertNoEvents();
8618 window->assertNoEvents();
8619}
8620
8621TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
8622 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08008623 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07008624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8625
8626 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8627 overlay->consumeMotionDown();
8628 window->consumeMotionDown();
8629 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8630 overlay->consumeMotionUp();
8631 window->consumeMotionUp();
8632
8633 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
8634 window->consumeMotionDown();
8635 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
8636 window->consumeMotionUp();
8637
8638 overlay->assertNoEvents();
8639 window->assertNoEvents();
8640}
8641
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00008642/**
8643 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
8644 * The scenario is as follows:
8645 * - The stylus interceptor overlay is configured as a spy window.
8646 * - The stylus interceptor spy receives the start of a new stylus gesture.
8647 * - It pilfers pointers and then configures itself to no longer be a spy.
8648 * - The stylus interceptor continues to receive the rest of the gesture.
8649 */
8650TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
8651 auto [overlay, window] = setupStylusOverlayScenario();
8652 overlay->setSpy(true);
8653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8654
8655 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
8656 overlay->consumeMotionDown();
8657 window->consumeMotionDown();
8658
8659 // The interceptor pilfers the pointers.
8660 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
8661 window->consumeMotionCancel();
8662
8663 // The interceptor configures itself so that it is no longer a spy.
8664 overlay->setSpy(false);
8665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
8666
8667 // It continues to receive the rest of the stylus gesture.
8668 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
8669 overlay->consumeMotionMove();
8670 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
8671 overlay->consumeMotionUp();
8672
8673 window->assertNoEvents();
8674}
8675
Prabir Pradhan5735a322022-04-11 17:23:34 +00008676struct User {
8677 int32_t mPid;
8678 int32_t mUid;
8679 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
8680 std::unique_ptr<InputDispatcher>& mDispatcher;
8681
8682 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
8683 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
8684
8685 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
8686 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
8687 ADISPLAY_ID_DEFAULT, {100, 200},
8688 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
8689 AMOTION_EVENT_INVALID_CURSOR_POSITION},
8690 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
8691 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
8692 }
8693
8694 InputEventInjectionResult injectTargetedKey(int32_t action) const {
Harry Cutts33476232023-01-30 19:57:29 +00008695 return inputdispatcher::injectKey(mDispatcher, action, /*repeatCount=*/0, ADISPLAY_ID_NONE,
Prabir Pradhan5735a322022-04-11 17:23:34 +00008696 InputEventInjectionSync::WAIT_FOR_RESULT,
Harry Cutts33476232023-01-30 19:57:29 +00008697 INJECT_EVENT_TIMEOUT, /*allowKeyRepeat=*/false, {mUid},
Prabir Pradhan5735a322022-04-11 17:23:34 +00008698 mPolicyFlags);
8699 }
8700
8701 sp<FakeWindowHandle> createWindow() const {
8702 std::shared_ptr<FakeApplicationHandle> overlayApplication =
8703 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07008704 sp<FakeWindowHandle> window =
8705 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
8706 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00008707 window->setOwnerInfo(mPid, mUid);
8708 return window;
8709 }
8710};
8711
8712using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
8713
8714TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
8715 auto owner = User(mDispatcher, 10, 11);
8716 auto window = owner.createWindow();
8717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8718
8719 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8720 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8721 window->consumeMotionDown();
8722
8723 setFocusedWindow(window);
8724 window->consumeFocusEvent(true);
8725
8726 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8727 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8728 window->consumeKeyDown(ADISPLAY_ID_NONE);
8729}
8730
8731TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
8732 auto owner = User(mDispatcher, 10, 11);
8733 auto window = owner.createWindow();
8734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
8735
8736 auto rando = User(mDispatcher, 20, 21);
8737 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8738 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8739
8740 setFocusedWindow(window);
8741 window->consumeFocusEvent(true);
8742
8743 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
8744 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
8745 window->assertNoEvents();
8746}
8747
8748TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
8749 auto owner = User(mDispatcher, 10, 11);
8750 auto window = owner.createWindow();
8751 auto spy = owner.createWindow();
8752 spy->setSpy(true);
8753 spy->setTrustedOverlay(true);
8754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
8755
8756 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8757 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8758 spy->consumeMotionDown();
8759 window->consumeMotionDown();
8760}
8761
8762TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
8763 auto owner = User(mDispatcher, 10, 11);
8764 auto window = owner.createWindow();
8765
8766 auto rando = User(mDispatcher, 20, 21);
8767 auto randosSpy = rando.createWindow();
8768 randosSpy->setSpy(true);
8769 randosSpy->setTrustedOverlay(true);
8770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8771
8772 // The event is targeted at owner's window, so injection should succeed, but the spy should
8773 // not receive the event.
8774 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8775 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8776 randosSpy->assertNoEvents();
8777 window->consumeMotionDown();
8778}
8779
8780TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
8781 auto owner = User(mDispatcher, 10, 11);
8782 auto window = owner.createWindow();
8783
8784 auto rando = User(mDispatcher, 20, 21);
8785 auto randosSpy = rando.createWindow();
8786 randosSpy->setSpy(true);
8787 randosSpy->setTrustedOverlay(true);
8788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
8789
8790 // A user that has injection permission can inject into any window.
8791 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8792 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
8793 ADISPLAY_ID_DEFAULT));
8794 randosSpy->consumeMotionDown();
8795 window->consumeMotionDown();
8796
8797 setFocusedWindow(randosSpy);
8798 randosSpy->consumeFocusEvent(true);
8799
8800 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
8801 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
8802 window->assertNoEvents();
8803}
8804
8805TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
8806 auto owner = User(mDispatcher, 10, 11);
8807 auto window = owner.createWindow();
8808
8809 auto rando = User(mDispatcher, 20, 21);
8810 auto randosWindow = rando.createWindow();
8811 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8812 randosWindow->setWatchOutsideTouch(true);
8813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8814
8815 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8816 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8817 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8818 window->consumeMotionDown();
8819 randosWindow->consumeMotionOutside();
8820}
8821
Garfield Tane84e6f92019-08-29 17:28:41 -07008822} // namespace android::inputdispatcher