blob: 7817eca43b9d20f8722b471cba541aaf175c7df2 [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 Vishniakou4cb50ca2020-05-26 21:43:02 -070032#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080033#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080034#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Garfield Tan1c7bc862020-01-28 13:24:04 -080036using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050037using android::gui::FocusRequest;
38using android::gui::TouchOcclusionMode;
39using android::gui::WindowInfo;
40using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080041using android::os::InputEventInjectionResult;
42using android::os::InputEventInjectionSync;
Garfield Tan1c7bc862020-01-28 13:24:04 -080043
Garfield Tane84e6f92019-08-29 17:28:41 -070044namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080045
Dominik Laskowski2f01d772022-03-23 16:01:29 -070046using namespace ftl::flag_operators;
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -080047using testing::AllOf;
Dominik Laskowski2f01d772022-03-23 16:01:29 -070048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049// An arbitrary time value.
Prabir Pradhan5735a322022-04-11 17:23:34 +000050static constexpr nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080051
52// An arbitrary device id.
Prabir Pradhan5735a322022-04-11 17:23:34 +000053static constexpr int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080054
Jeff Brownf086ddb2014-02-11 14:28:48 -080055// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000056static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
57static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080058
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080059static constexpr int32_t POINTER_1_DOWN =
60 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000061static constexpr int32_t POINTER_2_DOWN =
62 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000063static constexpr int32_t POINTER_3_DOWN =
64 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080065static constexpr int32_t POINTER_1_UP =
66 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
67
Antonio Kantek15beb512022-06-13 22:35:41 +000068// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000069static constexpr int32_t WINDOW_PID = 999;
70static constexpr int32_t WINDOW_UID = 1001;
71
Antonio Kantek15beb512022-06-13 22:35:41 +000072// The default pid and uid for the windows created on the secondary display by the test.
73static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
74static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
75
Prabir Pradhan5735a322022-04-11 17:23:34 +000076// The default policy flags to use for event injection by tests.
77static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000079// An arbitrary pid of the gesture monitor window
80static constexpr int32_t MONITOR_PID = 2001;
81
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080082static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
83
chaviwd1c23182019-12-20 18:44:56 -080084struct PointF {
85 float x;
86 float y;
87};
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Gang Wang342c9272020-01-13 13:15:04 -050089/**
90 * Return a DOWN key event with KEYCODE_A.
91 */
92static KeyEvent getTestKeyEvent() {
93 KeyEvent event;
94
Garfield Tanfbe732e2020-01-24 11:26:14 -080095 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
96 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
97 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050098 return event;
99}
100
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000101static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
102 ASSERT_EQ(expectedAction, receivedAction)
103 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
104 << MotionEvent::actionToString(receivedAction);
105}
106
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -0800107MATCHER_P(WithMotionAction, action, "MotionEvent with specified action") {
108 bool matches = action == arg.getAction();
109 if (!matches) {
110 *result_listener << "expected action " << MotionEvent::actionToString(action)
111 << ", but got " << MotionEvent::actionToString(arg.getAction());
112 }
113 if (action == AMOTION_EVENT_ACTION_CANCEL) {
114 if (!matches) {
115 *result_listener << "; ";
116 }
117 *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
118 matches &= (arg.getFlags() & AMOTION_EVENT_FLAG_CANCELED) != 0;
119 }
120 return matches;
121}
122
123MATCHER_P(WithSource, source, "InputEvent with specified source") {
124 *result_listener << "expected source " << inputEventSourceToString(source) << ", but got "
125 << inputEventSourceToString(arg.getSource());
126 return arg.getSource() == source;
127}
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// --- FakeInputDispatcherPolicy ---
130
131class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
132 InputDispatcherConfiguration mConfig;
133
Prabir Pradhanedd96402022-02-15 01:46:16 -0800134 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
135
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000137 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138
139public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000140 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800141
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800142 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700143 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
144 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
145 EXPECT_EQ(event.getDisplayId(), args.displayId);
146
147 const auto& keyEvent = static_cast<const KeyEvent&>(event);
148 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
149 EXPECT_EQ(keyEvent.getAction(), args.action);
150 });
Jackal Guof9696682018-10-05 12:23:23 +0800151 }
152
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700153 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
154 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
155 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
156 EXPECT_EQ(event.getDisplayId(), args.displayId);
157
158 const auto& motionEvent = static_cast<const MotionEvent&>(event);
159 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
160 EXPECT_EQ(motionEvent.getAction(), args.action);
161 EXPECT_EQ(motionEvent.getX(0), point.x);
162 EXPECT_EQ(motionEvent.getY(0), point.y);
163 EXPECT_EQ(motionEvent.getRawX(0), point.x);
164 EXPECT_EQ(motionEvent.getRawY(0), point.y);
165 });
Jackal Guof9696682018-10-05 12:23:23 +0800166 }
167
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700168 void assertFilterInputEventWasNotCalled() {
169 std::scoped_lock lock(mLock);
170 ASSERT_EQ(nullptr, mFilteredEvent);
171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800173 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700174 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800175 ASSERT_TRUE(mConfigurationChangedTime)
176 << "Timed out waiting for configuration changed call";
177 ASSERT_EQ(*mConfigurationChangedTime, when);
178 mConfigurationChangedTime = std::nullopt;
179 }
180
181 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700182 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800183 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800184 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800185 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
186 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
187 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
188 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
189 mLastNotifySwitch = std::nullopt;
190 }
191
chaviwfd6d3512019-03-25 13:23:49 -0700192 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700193 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800194 ASSERT_EQ(touchedToken, mOnPointerDownToken);
195 mOnPointerDownToken.clear();
196 }
197
198 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700199 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800200 ASSERT_TRUE(mOnPointerDownToken == nullptr)
201 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700202 }
203
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700204 // This function must be called soon after the expected ANR timer starts,
205 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500206 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700207 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500208 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800209 std::unique_lock lock(mLock);
210 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500211 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800212 ASSERT_NO_FATAL_FAILURE(
213 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500214 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700215 }
216
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000217 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800218 const sp<WindowInfoHandle>& window) {
219 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
220 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
221 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500222 }
223
Prabir Pradhanedd96402022-02-15 01:46:16 -0800224 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
225 const sp<IBinder>& expectedToken,
226 int32_t expectedPid) {
227 std::unique_lock lock(mLock);
228 android::base::ScopedLockAssertion assumeLocked(mLock);
229 AnrResult result;
230 ASSERT_NO_FATAL_FAILURE(result =
231 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
232 const auto& [token, pid] = result;
233 ASSERT_EQ(expectedToken, token);
234 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500235 }
236
Prabir Pradhanedd96402022-02-15 01:46:16 -0800237 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000238 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500239 std::unique_lock lock(mLock);
240 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800241 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
242 const auto& [token, _] = result;
243 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000244 }
245
Prabir Pradhanedd96402022-02-15 01:46:16 -0800246 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
247 int32_t expectedPid) {
248 std::unique_lock lock(mLock);
249 android::base::ScopedLockAssertion assumeLocked(mLock);
250 AnrResult result;
251 ASSERT_NO_FATAL_FAILURE(
252 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
253 const auto& [token, pid] = result;
254 ASSERT_EQ(expectedToken, token);
255 ASSERT_EQ(expectedPid, pid);
256 }
257
258 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000259 sp<IBinder> getResponsiveWindowToken() {
260 std::unique_lock lock(mLock);
261 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800262 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
263 const auto& [token, _] = result;
264 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700265 }
266
267 void assertNotifyAnrWasNotCalled() {
268 std::scoped_lock lock(mLock);
269 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800270 ASSERT_TRUE(mAnrWindows.empty());
271 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500272 << "ANR was not called, but please also consume the 'connection is responsive' "
273 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700274 }
275
Garfield Tan1c7bc862020-01-28 13:24:04 -0800276 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
277 mConfig.keyRepeatTimeout = timeout;
278 mConfig.keyRepeatDelay = delay;
279 }
280
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000281 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800282 std::unique_lock lock(mLock);
283 base::ScopedLockAssertion assumeLocked(mLock);
284
285 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
286 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000287 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800288 enabled;
289 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000290 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
291 << ") to be called.";
292 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800293 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000294 auto request = *mPointerCaptureRequest;
295 mPointerCaptureRequest.reset();
296 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800297 }
298
299 void assertSetPointerCaptureNotCalled() {
300 std::unique_lock lock(mLock);
301 base::ScopedLockAssertion assumeLocked(mLock);
302
303 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000304 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800305 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000306 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800307 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000308 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800309 }
310
arthurhungf452d0b2021-01-06 00:19:52 +0800311 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
312 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800313 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800314 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800315 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800316 }
317
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800318 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
319 std::unique_lock lock(mLock);
320 base::ScopedLockAssertion assumeLocked(mLock);
321 std::optional<sp<IBinder>> receivedToken =
322 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
323 mNotifyInputChannelBroken);
324 ASSERT_TRUE(receivedToken.has_value());
325 ASSERT_EQ(token, *receivedToken);
326 }
327
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800328 /**
329 * Set policy timeout. A value of zero means next key will not be intercepted.
330 */
331 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
332 mInterceptKeyTimeout = timeout;
333 }
334
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700336 std::mutex mLock;
337 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
338 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
339 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
340 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800341
Prabir Pradhan99987712020-11-10 18:43:05 -0800342 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000343
344 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800345
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700346 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700347 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800348 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
349 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700350 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800351 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
352 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700353
arthurhungf452d0b2021-01-06 00:19:52 +0800354 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800355 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800356
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800357 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
358
Prabir Pradhanedd96402022-02-15 01:46:16 -0800359 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
360 // for a specific container to become non-empty. When the container is non-empty, return the
361 // first entry from the container and erase it.
362 template <class T>
363 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
364 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
365 // If there is an ANR, Dispatcher won't be idle because there are still events
366 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
367 // before checking if ANR was called.
368 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
369 // to provide it some time to act. 100ms seems reasonable.
370 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
371 const std::chrono::time_point start = std::chrono::steady_clock::now();
372 std::optional<T> token =
373 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
374 if (!token.has_value()) {
375 ADD_FAILURE() << "Did not receive the ANR callback";
376 return {};
377 }
378
379 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
380 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
381 // the dispatcher started counting before this function was called
382 if (std::chrono::abs(timeout - waited) > 100ms) {
383 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
384 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
385 << "ms, but waited "
386 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
387 << "ms instead";
388 }
389 return *token;
390 }
391
392 template <class T>
393 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
394 std::queue<T>& storage,
395 std::unique_lock<std::mutex>& lock,
396 std::condition_variable& condition)
397 REQUIRES(mLock) {
398 condition.wait_for(lock, timeout,
399 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
400 if (storage.empty()) {
401 ADD_FAILURE() << "Did not receive the expected callback";
402 return std::nullopt;
403 }
404 T item = storage.front();
405 storage.pop();
406 return std::make_optional(item);
407 }
408
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600409 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700410 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800411 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 }
413
Prabir Pradhanedd96402022-02-15 01:46:16 -0800414 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
415 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700416 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800417 ASSERT_TRUE(pid.has_value());
418 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700419 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500420 }
421
Prabir Pradhanedd96402022-02-15 01:46:16 -0800422 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
423 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500424 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800425 ASSERT_TRUE(pid.has_value());
426 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500427 mNotifyAnr.notify_all();
428 }
429
430 void notifyNoFocusedWindowAnr(
431 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
432 std::scoped_lock lock(mLock);
433 mAnrApplications.push(applicationHandle);
434 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 }
436
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800437 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
438 std::scoped_lock lock(mLock);
439 mBrokenInputChannels.push(connectionToken);
440 mNotifyInputChannelBroken.notify_all();
441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600443 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700444
Chris Yef59a2f42020-10-16 12:55:26 -0700445 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
446 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
447 const std::vector<float>& values) override {}
448
449 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
450 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000451
Chris Yefb552902021-02-03 17:18:37 -0800452 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
453
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600454 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455 *outConfig = mConfig;
456 }
457
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600458 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700459 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800460 switch (inputEvent->getType()) {
461 case AINPUT_EVENT_TYPE_KEY: {
462 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800463 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800464 break;
465 }
466
467 case AINPUT_EVENT_TYPE_MOTION: {
468 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800469 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800470 break;
471 }
472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 return true;
474 }
475
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800476 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
477 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
478 // Clear intercept state when we handled the event.
479 mInterceptKeyTimeout = 0ms;
480 }
481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600483 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600485 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800486 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
487 // Clear intercept state so we could dispatch the event in next wake.
488 mInterceptKeyTimeout = 0ms;
489 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 }
491
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600492 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 return false;
494 }
495
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600496 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
497 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700498 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800499 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
500 * essentially a passthrough for notifySwitch.
501 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800502 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 }
504
Sean Stoutb4e0a592021-02-23 07:34:53 -0800505 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600507 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700508 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700509 mOnPointerDownToken = newToken;
510 }
511
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000512 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800513 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000514 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800515 mPointerCaptureChangedCondition.notify_all();
516 }
517
arthurhungf452d0b2021-01-06 00:19:52 +0800518 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
519 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800520 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800521 mDropTargetWindowToken = token;
522 }
523
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700524 void assertFilterInputEventWasCalledInternal(
525 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700526 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800527 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700528 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800529 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531};
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533// --- InputDispatcherTest ---
534
535class InputDispatcherTest : public testing::Test {
536protected:
537 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700538 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000540 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700541 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800542 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800543 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000544 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700545 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 }
547
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000548 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700549 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700551 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700553
554 /**
555 * Used for debugging when writing the test
556 */
557 void dumpDispatcherState() {
558 std::string dump;
559 mDispatcher->dump(dump);
560 std::stringstream ss(dump);
561 std::string to;
562
563 while (std::getline(ss, to, '\n')) {
564 ALOGE("%s", to.c_str());
565 }
566 }
Vishnu Nair958da932020-08-21 17:12:37 -0700567
chaviw3277faf2021-05-19 16:45:23 -0500568 void setFocusedWindow(const sp<WindowInfoHandle>& window,
569 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700570 FocusRequest request;
571 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000572 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700573 if (focusedWindow) {
574 request.focusedToken = focusedWindow->getToken();
575 }
576 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
577 request.displayId = window->getInfo()->displayId;
578 mDispatcher->setFocusedWindow(request);
579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580};
581
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
583 KeyEvent event;
584
585 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800586 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
587 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600588 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
589 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800590 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000591 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
592 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 << "Should reject key events with undefined action.";
594
595 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800596 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
597 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600598 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000600 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
601 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject key events with ACTION_MULTIPLE.";
603}
604
605TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
606 MotionEvent event;
607 PointerProperties pointerProperties[MAX_POINTERS + 1];
608 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800609 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 pointerProperties[i].clear();
611 pointerProperties[i].id = i;
612 pointerCoords[i].clear();
613 }
614
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800615 // Some constants commonly used below
616 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
617 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
618 constexpr int32_t metaState = AMETA_NONE;
619 constexpr MotionClassification classification = MotionClassification::NONE;
620
chaviw9eaa22c2020-07-01 16:21:27 -0700621 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800623 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700624 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
625 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700626 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
627 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700628 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000630 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
631 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 << "Should reject motion events with undefined action.";
633
634 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800635 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800636 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
637 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
638 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
639 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500640 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800641 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000642 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
643 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 << "Should reject motion events with pointer down index too large.";
645
Garfield Tanfbe732e2020-01-24 11:26:14 -0800646 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700647 AMOTION_EVENT_ACTION_POINTER_DOWN |
648 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700649 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
650 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700651 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500652 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800653 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000654 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
655 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 << "Should reject motion events with pointer down index too small.";
657
658 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800659 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800660 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
661 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
663 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500664 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000666 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
667 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 << "Should reject motion events with pointer up index too large.";
669
Garfield Tanfbe732e2020-01-24 11:26:14 -0800670 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700671 AMOTION_EVENT_ACTION_POINTER_UP |
672 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700673 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
674 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700675 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500676 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000678 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
679 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 << "Should reject motion events with pointer up index too small.";
681
682 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800683 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
684 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700685 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700686 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
687 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700688 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800689 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000690 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
691 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 << "Should reject motion events with 0 pointers.";
693
Garfield Tanfbe732e2020-01-24 11:26:14 -0800694 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
695 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700696 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700697 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
698 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700699 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800700 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000701 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
702 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 << "Should reject motion events with more than MAX_POINTERS pointers.";
704
705 // Rejects motion events with invalid pointer ids.
706 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800707 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
708 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700709 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700710 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
711 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700712 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800713 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000714 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
715 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 << "Should reject motion events with pointer ids less than 0.";
717
718 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800719 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
720 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700721 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700722 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
723 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800725 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000726 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
727 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
729
730 // Rejects motion events with duplicate pointer ids.
731 pointerProperties[0].id = 1;
732 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800733 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
734 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700735 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700736 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
737 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700738 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800739 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000740 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
741 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 << "Should reject motion events with duplicate pointer ids.";
743}
744
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800745/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
746
747TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
748 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800749 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800750 mDispatcher->notifyConfigurationChanged(&args);
751 ASSERT_TRUE(mDispatcher->waitForIdle());
752
753 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
754}
755
756TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800757 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
758 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800759 mDispatcher->notifySwitch(&args);
760
761 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
762 args.policyFlags |= POLICY_FLAG_TRUSTED;
763 mFakePolicy->assertNotifySwitchWasCalled(args);
764}
765
Arthur Hungb92218b2018-08-14 12:00:21 +0800766// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700767static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700768// Default input dispatching timeout if there is no focused application or paused window
769// from which to determine an appropriate dispatching timeout.
770static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
771 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
772 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800773
774class FakeApplicationHandle : public InputApplicationHandle {
775public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700776 FakeApplicationHandle() {
777 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700778 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500779 mInfo.dispatchingTimeoutMillis =
780 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700781 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800782 virtual ~FakeApplicationHandle() {}
783
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000784 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700785
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500786 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
787 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700788 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800789};
790
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800791class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800792public:
Garfield Tan15601662020-09-22 15:32:38 -0700793 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800794 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700795 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800796 }
797
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800798 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700799 InputEvent* event;
800 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
801 if (!consumeSeq) {
802 return nullptr;
803 }
804 finishEvent(*consumeSeq);
805 return event;
806 }
807
808 /**
809 * Receive an event without acknowledging it.
810 * Return the sequence number that could later be used to send finished signal.
811 */
812 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800813 uint32_t consumeSeq;
814 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800815
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816 std::chrono::time_point start = std::chrono::steady_clock::now();
817 status_t status = WOULD_BLOCK;
818 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800819 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800820 &event);
821 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
822 if (elapsed > 100ms) {
823 break;
824 }
825 }
826
827 if (status == WOULD_BLOCK) {
828 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700829 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800830 }
831
832 if (status != OK) {
833 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700834 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800835 }
836 if (event == nullptr) {
837 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700838 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800839 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700840 if (outEvent != nullptr) {
841 *outEvent = event;
842 }
843 return consumeSeq;
844 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800845
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700846 /**
847 * To be used together with "receiveEvent" to complete the consumption of an event.
848 */
849 void finishEvent(uint32_t consumeSeq) {
850 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
851 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800852 }
853
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000854 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
855 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
856 ASSERT_EQ(OK, status);
857 }
858
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000859 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
860 std::optional<int32_t> expectedDisplayId,
861 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800862 InputEvent* event = consume();
863
864 ASSERT_NE(nullptr, event) << mName.c_str()
865 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800866 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700867 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800868 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800869
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000870 if (expectedDisplayId.has_value()) {
871 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
872 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800873
Tiger Huang8664f8c2018-10-11 19:14:35 +0800874 switch (expectedEventType) {
875 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800876 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
877 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000878 if (expectedFlags.has_value()) {
879 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
880 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800881 break;
882 }
883 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800884 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000885 assertMotionAction(expectedAction, motionEvent.getAction());
886
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000887 if (expectedFlags.has_value()) {
888 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
889 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800890 break;
891 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100892 case AINPUT_EVENT_TYPE_FOCUS: {
893 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
894 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800895 case AINPUT_EVENT_TYPE_CAPTURE: {
896 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
897 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000898 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
899 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
900 }
arthurhungb89ccb02020-12-30 16:19:01 +0800901 case AINPUT_EVENT_TYPE_DRAG: {
902 FAIL() << "Use 'consumeDragEvent' for DRAG events";
903 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800904 default: {
905 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
906 }
907 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800908 }
909
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100910 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
911 InputEvent* event = consume();
912 ASSERT_NE(nullptr, event) << mName.c_str()
913 << ": consumer should have returned non-NULL event.";
914 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
915 << "Got " << inputEventTypeToString(event->getType())
916 << " event instead of FOCUS event";
917
918 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
919 << mName.c_str() << ": event displayId should always be NONE.";
920
921 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
922 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100923 }
924
Prabir Pradhan99987712020-11-10 18:43:05 -0800925 void consumeCaptureEvent(bool hasCapture) {
926 const InputEvent* event = consume();
927 ASSERT_NE(nullptr, event) << mName.c_str()
928 << ": consumer should have returned non-NULL event.";
929 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
930 << "Got " << inputEventTypeToString(event->getType())
931 << " event instead of CAPTURE event";
932
933 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
934 << mName.c_str() << ": event displayId should always be NONE.";
935
936 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
937 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
938 }
939
arthurhungb89ccb02020-12-30 16:19:01 +0800940 void consumeDragEvent(bool isExiting, float x, float y) {
941 const InputEvent* event = consume();
942 ASSERT_NE(nullptr, event) << mName.c_str()
943 << ": consumer should have returned non-NULL event.";
944 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
945 << "Got " << inputEventTypeToString(event->getType())
946 << " event instead of DRAG event";
947
948 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
949 << mName.c_str() << ": event displayId should always be NONE.";
950
951 const auto& dragEvent = static_cast<const DragEvent&>(*event);
952 EXPECT_EQ(isExiting, dragEvent.isExiting());
953 EXPECT_EQ(x, dragEvent.getX());
954 EXPECT_EQ(y, dragEvent.getY());
955 }
956
Antonio Kantekf16f2832021-09-28 04:39:20 +0000957 void consumeTouchModeEvent(bool inTouchMode) {
958 const InputEvent* event = consume();
959 ASSERT_NE(nullptr, event) << mName.c_str()
960 << ": consumer should have returned non-NULL event.";
961 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
962 << "Got " << inputEventTypeToString(event->getType())
963 << " event instead of TOUCH_MODE event";
964
965 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
966 << mName.c_str() << ": event displayId should always be NONE.";
967 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
968 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
969 }
970
chaviwd1c23182019-12-20 18:44:56 -0800971 void assertNoEvents() {
972 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 if (event == nullptr) {
974 return;
975 }
976 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
977 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
978 ADD_FAILURE() << "Received key event "
979 << KeyEvent::actionToString(keyEvent.getAction());
980 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
981 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
982 ADD_FAILURE() << "Received motion event "
983 << MotionEvent::actionToString(motionEvent.getAction());
984 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
985 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
986 ADD_FAILURE() << "Received focus event, hasFocus = "
987 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800988 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
989 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
990 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
991 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000992 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
993 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
994 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
995 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 }
997 FAIL() << mName.c_str()
998 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800999 }
1000
1001 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
1002
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001003 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
1004
chaviwd1c23182019-12-20 18:44:56 -08001005protected:
1006 std::unique_ptr<InputConsumer> mConsumer;
1007 PreallocatedInputEventFactory mEventFactory;
1008
1009 std::string mName;
1010};
1011
chaviw3277faf2021-05-19 16:45:23 -05001012class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -08001013public:
1014 static const int32_t WIDTH = 600;
1015 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -08001016
Chris Yea209fde2020-07-22 13:54:51 -07001017 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001018 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001019 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -08001020 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001021 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -07001022 base::Result<std::unique_ptr<InputChannel>> channel =
1023 dispatcher->createInputChannel(name);
1024 token = (*channel)->getConnectionToken();
1025 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001026 }
1027
1028 inputApplicationHandle->updateInfo();
1029 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1030
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001031 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001032 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001033 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001034 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001035 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001036 mInfo.frameLeft = 0;
1037 mInfo.frameTop = 0;
1038 mInfo.frameRight = WIDTH;
1039 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001040 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001041 mInfo.globalScaleFactor = 1.0;
1042 mInfo.touchableRegion.clear();
1043 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001044 mInfo.ownerPid = WINDOW_PID;
1045 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001046 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001047 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001048 }
1049
Arthur Hungabbb9d82021-09-01 14:52:30 +00001050 sp<FakeWindowHandle> clone(
1051 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001052 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001053 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001054 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1055 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001056 return handle;
1057 }
1058
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001059 void setTouchable(bool touchable) {
1060 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1061 }
chaviwd1c23182019-12-20 18:44:56 -08001062
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001063 void setFocusable(bool focusable) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1065 }
1066
1067 void setVisible(bool visible) {
1068 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1069 }
Vishnu Nair958da932020-08-21 17:12:37 -07001070
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001071 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001072 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001073 }
1074
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001075 void setPaused(bool paused) {
1076 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1077 }
1078
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001079 void setPreventSplitting(bool preventSplitting) {
1080 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001081 }
1082
1083 void setSlippery(bool slippery) {
1084 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1085 }
1086
1087 void setWatchOutsideTouch(bool watchOutside) {
1088 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1089 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001090
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001091 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1092
1093 void setInterceptsStylus(bool interceptsStylus) {
1094 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1095 }
1096
1097 void setDropInput(bool dropInput) {
1098 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1099 }
1100
1101 void setDropInputIfObscured(bool dropInputIfObscured) {
1102 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1103 }
1104
1105 void setNoInputChannel(bool noInputChannel) {
1106 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1107 }
1108
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001109 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1110
chaviw3277faf2021-05-19 16:45:23 -05001111 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001112
Bernardo Rufino7393d172021-02-26 13:56:11 +00001113 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1114
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001115 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001116 mInfo.frameLeft = frame.left;
1117 mInfo.frameTop = frame.top;
1118 mInfo.frameRight = frame.right;
1119 mInfo.frameBottom = frame.bottom;
1120 mInfo.touchableRegion.clear();
1121 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001122
1123 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1124 ui::Transform translate;
1125 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1126 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001127 }
1128
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001129 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1130
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001131 void setIsWallpaper(bool isWallpaper) {
1132 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1133 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001134
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001135 void setDupTouchToWallpaper(bool hasWallpaper) {
1136 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1137 }
chaviwd1c23182019-12-20 18:44:56 -08001138
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001139 void setTrustedOverlay(bool trustedOverlay) {
1140 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1141 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001142
chaviw9eaa22c2020-07-01 16:21:27 -07001143 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1144 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1145 }
1146
1147 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001148
yunho.shinf4a80b82020-11-16 21:13:57 +09001149 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1150
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001151 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1152 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1153 expectedFlags);
1154 }
1155
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001156 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1157 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1158 }
1159
Svet Ganov5d3bc372020-01-26 23:11:07 -08001160 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001161 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001162 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1163 expectedFlags);
1164 }
1165
1166 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001167 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001168 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1169 expectedFlags);
1170 }
1171
1172 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001173 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001174 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1175 }
1176
1177 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1178 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001179 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1180 expectedFlags);
1181 }
1182
Svet Ganov5d3bc372020-01-26 23:11:07 -08001183 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001184 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1185 int32_t expectedFlags = 0) {
1186 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1187 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001188 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1189 }
1190
1191 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001192 int32_t expectedFlags = 0) {
1193 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1194 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001195 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1196 }
1197
1198 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001199 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001200 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1201 expectedFlags);
1202 }
1203
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001204 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1205 int32_t expectedFlags = 0) {
1206 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1207 expectedFlags);
1208 }
1209
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001210 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1211 int32_t expectedFlags = 0) {
1212 InputEvent* event = consume();
1213 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1214 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1215 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1216 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1217 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1218 }
1219
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001220 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1221 ASSERT_NE(mInputReceiver, nullptr)
1222 << "Cannot consume events from a window with no receiver";
1223 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1224 }
1225
Prabir Pradhan99987712020-11-10 18:43:05 -08001226 void consumeCaptureEvent(bool hasCapture) {
1227 ASSERT_NE(mInputReceiver, nullptr)
1228 << "Cannot consume events from a window with no receiver";
1229 mInputReceiver->consumeCaptureEvent(hasCapture);
1230 }
1231
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001232 void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher) {
1233 MotionEvent* motionEvent = consumeMotion();
1234 ASSERT_NE(nullptr, motionEvent) << "Did not get a motion event";
1235 ASSERT_THAT(*motionEvent, matcher);
1236 }
1237
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001238 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1239 std::optional<int32_t> expectedDisplayId,
1240 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001241 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1242 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1243 expectedFlags);
1244 }
1245
arthurhungb89ccb02020-12-30 16:19:01 +08001246 void consumeDragEvent(bool isExiting, float x, float y) {
1247 mInputReceiver->consumeDragEvent(isExiting, x, y);
1248 }
1249
Antonio Kantekf16f2832021-09-28 04:39:20 +00001250 void consumeTouchModeEvent(bool inTouchMode) {
1251 ASSERT_NE(mInputReceiver, nullptr)
1252 << "Cannot consume events from a window with no receiver";
1253 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1254 }
1255
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001256 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001257 if (mInputReceiver == nullptr) {
1258 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1259 return std::nullopt;
1260 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001261 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001262 }
1263
1264 void finishEvent(uint32_t sequenceNum) {
1265 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1266 mInputReceiver->finishEvent(sequenceNum);
1267 }
1268
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001269 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1270 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1271 mInputReceiver->sendTimeline(inputEventId, timeline);
1272 }
1273
chaviwaf87b3e2019-10-01 16:59:28 -07001274 InputEvent* consume() {
1275 if (mInputReceiver == nullptr) {
1276 return nullptr;
1277 }
1278 return mInputReceiver->consume();
1279 }
1280
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001281 MotionEvent* consumeMotion() {
1282 InputEvent* event = consume();
1283 if (event == nullptr) {
1284 ADD_FAILURE() << "Consume failed : no event";
1285 return nullptr;
1286 }
1287 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1288 ADD_FAILURE() << "Instead of motion event, got "
1289 << inputEventTypeToString(event->getType());
1290 return nullptr;
1291 }
1292 return static_cast<MotionEvent*>(event);
1293 }
1294
Arthur Hungb92218b2018-08-14 12:00:21 +08001295 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001296 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001297 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001298 return; // Can't receive events if the window does not have input channel
1299 }
1300 ASSERT_NE(nullptr, mInputReceiver)
1301 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001302 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001303 }
1304
chaviwaf87b3e2019-10-01 16:59:28 -07001305 sp<IBinder> getToken() { return mInfo.token; }
1306
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001307 const std::string& getName() { return mName; }
1308
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001309 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1310 mInfo.ownerPid = ownerPid;
1311 mInfo.ownerUid = ownerUid;
1312 }
1313
Prabir Pradhanedd96402022-02-15 01:46:16 -08001314 int32_t getPid() const { return mInfo.ownerPid; }
1315
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001316 void destroyReceiver() { mInputReceiver = nullptr; }
1317
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001318 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1319
chaviwd1c23182019-12-20 18:44:56 -08001320private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001321 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001322 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001323 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001324};
1325
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001326std::atomic<int32_t> FakeWindowHandle::sId{1};
1327
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001328static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001329 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001330 int32_t displayId = ADISPLAY_ID_NONE,
1331 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001332 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001333 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1334 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001335 KeyEvent event;
1336 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1337
1338 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001339 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001340 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1341 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001342
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001343 if (!allowKeyRepeat) {
1344 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1345 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001346 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001347 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001348}
1349
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001350static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001351 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001352 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1353}
1354
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001355// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1356// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1357// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001358static InputEventInjectionResult injectKeyDownNoRepeat(
1359 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001360 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1361 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1362 /* allowKeyRepeat */ false);
1363}
1364
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001365static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001366 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001367 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1368}
1369
Garfield Tandf26e862020-07-01 20:18:19 -07001370class PointerBuilder {
1371public:
1372 PointerBuilder(int32_t id, int32_t toolType) {
1373 mProperties.clear();
1374 mProperties.id = id;
1375 mProperties.toolType = toolType;
1376 mCoords.clear();
1377 }
1378
1379 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1380
1381 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1382
1383 PointerBuilder& axis(int32_t axis, float value) {
1384 mCoords.setAxisValue(axis, value);
1385 return *this;
1386 }
1387
1388 PointerProperties buildProperties() const { return mProperties; }
1389
1390 PointerCoords buildCoords() const { return mCoords; }
1391
1392private:
1393 PointerProperties mProperties;
1394 PointerCoords mCoords;
1395};
1396
1397class MotionEventBuilder {
1398public:
1399 MotionEventBuilder(int32_t action, int32_t source) {
1400 mAction = action;
1401 mSource = source;
1402 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1403 }
1404
1405 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1406 mEventTime = eventTime;
1407 return *this;
1408 }
1409
1410 MotionEventBuilder& displayId(int32_t displayId) {
1411 mDisplayId = displayId;
1412 return *this;
1413 }
1414
1415 MotionEventBuilder& actionButton(int32_t actionButton) {
1416 mActionButton = actionButton;
1417 return *this;
1418 }
1419
arthurhung6d4bed92021-03-17 11:59:33 +08001420 MotionEventBuilder& buttonState(int32_t buttonState) {
1421 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001422 return *this;
1423 }
1424
1425 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1426 mRawXCursorPosition = rawXCursorPosition;
1427 return *this;
1428 }
1429
1430 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1431 mRawYCursorPosition = rawYCursorPosition;
1432 return *this;
1433 }
1434
1435 MotionEventBuilder& pointer(PointerBuilder pointer) {
1436 mPointers.push_back(pointer);
1437 return *this;
1438 }
1439
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001440 MotionEventBuilder& addFlag(uint32_t flags) {
1441 mFlags |= flags;
1442 return *this;
1443 }
1444
Garfield Tandf26e862020-07-01 20:18:19 -07001445 MotionEvent build() {
1446 std::vector<PointerProperties> pointerProperties;
1447 std::vector<PointerCoords> pointerCoords;
1448 for (const PointerBuilder& pointer : mPointers) {
1449 pointerProperties.push_back(pointer.buildProperties());
1450 pointerCoords.push_back(pointer.buildCoords());
1451 }
1452
1453 // Set mouse cursor position for the most common cases to avoid boilerplate.
1454 if (mSource == AINPUT_SOURCE_MOUSE &&
1455 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1456 mPointers.size() == 1) {
1457 mRawXCursorPosition = pointerCoords[0].getX();
1458 mRawYCursorPosition = pointerCoords[0].getY();
1459 }
1460
1461 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001462 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001463 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001464 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001465 mButtonState, MotionClassification::NONE, identityTransform,
1466 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001467 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1468 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001469
1470 return event;
1471 }
1472
1473private:
1474 int32_t mAction;
1475 int32_t mSource;
1476 nsecs_t mEventTime;
1477 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1478 int32_t mActionButton{0};
1479 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001480 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001481 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1482 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1483
1484 std::vector<PointerBuilder> mPointers;
1485};
1486
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001488 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001489 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001490 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1491 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1492 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1493 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001494}
1495
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001497 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001498 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001499 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001500 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1501 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001502 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001503 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1504 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001505 MotionEvent event = MotionEventBuilder(action, source)
1506 .displayId(displayId)
1507 .eventTime(eventTime)
1508 .rawXCursorPosition(cursorPosition.x)
1509 .rawYCursorPosition(cursorPosition.y)
1510 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1511 .x(position.x)
1512 .y(position.y))
1513 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001514
1515 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001516 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1517 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001518}
1519
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001520static InputEventInjectionResult injectMotionDown(
1521 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1522 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001523 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001524}
1525
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001526static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527 int32_t source, int32_t displayId,
1528 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001529 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001530}
1531
Jackal Guof9696682018-10-05 12:23:23 +08001532static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1533 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1534 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001535 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1536 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1537 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001538
1539 return args;
1540}
1541
chaviwd1c23182019-12-20 18:44:56 -08001542static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1543 const std::vector<PointF>& points) {
1544 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001545 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1546 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1547 }
1548
chaviwd1c23182019-12-20 18:44:56 -08001549 PointerProperties pointerProperties[pointerCount];
1550 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001551
chaviwd1c23182019-12-20 18:44:56 -08001552 for (size_t i = 0; i < pointerCount; i++) {
1553 pointerProperties[i].clear();
1554 pointerProperties[i].id = i;
1555 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001556
chaviwd1c23182019-12-20 18:44:56 -08001557 pointerCoords[i].clear();
1558 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1559 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1560 }
Jackal Guof9696682018-10-05 12:23:23 +08001561
1562 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1563 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001564 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001565 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1566 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001567 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1568 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001569 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1570 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001571
1572 return args;
1573}
1574
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001575static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1576 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1577}
1578
chaviwd1c23182019-12-20 18:44:56 -08001579static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1580 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1581}
1582
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001583static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1584 const PointerCaptureRequest& request) {
1585 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001586}
1587
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001588/**
1589 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1590 * broken channel.
1591 */
1592TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1593 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1594 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001595 sp<FakeWindowHandle>::make(application, mDispatcher,
1596 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001597
1598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1599
1600 // Window closes its channel, but the window remains.
1601 window->destroyReceiver();
1602 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1603}
1604
Arthur Hungb92218b2018-08-14 12:00:21 +08001605TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001606 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001607 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1608 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001609
Arthur Hung72d8dc32020-03-28 00:48:39 +00001610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001614
1615 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001616 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001617}
1618
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001619TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1620 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001621 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1622 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001623
1624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1625 // Inject a MotionEvent to an unknown display.
1626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1627 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1629
1630 // Window should receive motion event.
1631 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1632}
1633
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001634/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001635 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001636 * This test serves as a sanity check for the next test, where setInputWindows is
1637 * called twice.
1638 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001639TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001640 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001641 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1642 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001643 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001644
1645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1648 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001650
1651 // Window should receive motion event.
1652 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1653}
1654
1655/**
1656 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001657 */
1658TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001659 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001660 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1661 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001662 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001663
1664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1668 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001670
1671 // Window should receive motion event.
1672 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1673}
1674
Arthur Hungb92218b2018-08-14 12:00:21 +08001675// The foreground window should receive the first touch down event.
1676TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001677 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001678 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001679 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001680 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001681 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001682
Arthur Hung72d8dc32020-03-28 00:48:39 +00001683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1685 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001687
1688 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001689 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001690 windowSecond->assertNoEvents();
1691}
1692
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001693/**
1694 * Two windows: A top window, and a wallpaper behind the window.
1695 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1696 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001697 * 1. foregroundWindow <-- dup touch to wallpaper
1698 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001699 */
1700TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1702 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001703 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001704 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001705 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001706 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001707 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001708 constexpr int expectedWallpaperFlags =
1709 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1710
1711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1712 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1713 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1714 {100, 200}))
1715 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1716
1717 // Both foreground window and its wallpaper should receive the touch down
1718 foregroundWindow->consumeMotionDown();
1719 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1720
1721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1722 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1723 ADISPLAY_ID_DEFAULT, {110, 200}))
1724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1725
1726 foregroundWindow->consumeMotionMove();
1727 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1728
1729 // Now the foreground window goes away, but the wallpaper stays
1730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1731 foregroundWindow->consumeMotionCancel();
1732 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1733 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1734}
1735
1736/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001737 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1738 * with the following differences:
1739 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1740 * clean up the connection.
1741 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1742 * Ensure that there's no crash in the dispatcher.
1743 */
1744TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1745 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1746 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001747 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001748 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001749 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001750 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001751 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001752 constexpr int expectedWallpaperFlags =
1753 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1754
1755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1757 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1758 {100, 200}))
1759 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1760
1761 // Both foreground window and its wallpaper should receive the touch down
1762 foregroundWindow->consumeMotionDown();
1763 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1764
1765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1766 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1767 ADISPLAY_ID_DEFAULT, {110, 200}))
1768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1769
1770 foregroundWindow->consumeMotionMove();
1771 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1772
1773 // Wallpaper closes its channel, but the window remains.
1774 wallpaperWindow->destroyReceiver();
1775 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1776
1777 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1778 // is no longer valid.
1779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1780 foregroundWindow->consumeMotionCancel();
1781}
1782
1783/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001784 * A single window that receives touch (on top), and a wallpaper window underneath it.
1785 * The top window gets a multitouch gesture.
1786 * Ensure that wallpaper gets the same gesture.
1787 */
1788TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1789 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1790 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001791 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001792 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001793
1794 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001795 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001796 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001797 constexpr int expectedWallpaperFlags =
1798 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1799
1800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1801
1802 // Touch down on top window
1803 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1804 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1805 {100, 100}))
1806 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1807
1808 // Both top window and its wallpaper should receive the touch down
1809 window->consumeMotionDown();
1810 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1811
1812 // Second finger down on the top window
1813 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001814 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001815 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1816 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1817 .x(100)
1818 .y(100))
1819 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1820 .x(150)
1821 .y(150))
1822 .build();
1823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1824 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1825 InputEventInjectionSync::WAIT_FOR_RESULT))
1826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1827
1828 window->consumeMotionPointerDown(1 /* pointerIndex */);
1829 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1830 expectedWallpaperFlags);
1831 window->assertNoEvents();
1832 wallpaperWindow->assertNoEvents();
1833}
1834
1835/**
1836 * Two windows: a window on the left and window on the right.
1837 * A third window, wallpaper, is behind both windows, and spans both top windows.
1838 * The first touch down goes to the left window. A second pointer touches down on the right window.
1839 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1840 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1841 * ACTION_POINTER_DOWN(1).
1842 */
1843TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1844 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1845 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001846 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001847 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001848 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001849
1850 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001851 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001852 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001853 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001854
1855 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001856 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001857 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001858 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001859 constexpr int expectedWallpaperFlags =
1860 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1861
1862 mDispatcher->setInputWindows(
1863 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1864
1865 // Touch down on left window
1866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1868 {100, 100}))
1869 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1870
1871 // Both foreground window and its wallpaper should receive the touch down
1872 leftWindow->consumeMotionDown();
1873 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1874
1875 // Second finger down on the right window
1876 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001877 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001878 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1879 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1880 .x(100)
1881 .y(100))
1882 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1883 .x(300)
1884 .y(100))
1885 .build();
1886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1887 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1888 InputEventInjectionSync::WAIT_FOR_RESULT))
1889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1890
1891 leftWindow->consumeMotionMove();
1892 // Since the touch is split, right window gets ACTION_DOWN
1893 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1894 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1895 expectedWallpaperFlags);
1896
1897 // Now, leftWindow, which received the first finger, disappears.
1898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1899 leftWindow->consumeMotionCancel();
1900 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1901 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1902
1903 // The pointer that's still down on the right window moves, and goes to the right window only.
1904 // As far as the dispatcher's concerned though, both pointers are still present.
1905 const MotionEvent secondFingerMoveEvent =
1906 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1907 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1908 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1909 .x(100)
1910 .y(100))
1911 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1912 .x(310)
1913 .y(110))
1914 .build();
1915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1916 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1917 InputEventInjectionSync::WAIT_FOR_RESULT));
1918 rightWindow->consumeMotionMove();
1919
1920 leftWindow->assertNoEvents();
1921 rightWindow->assertNoEvents();
1922 wallpaperWindow->assertNoEvents();
1923}
1924
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001925/**
1926 * On the display, have a single window, and also an area where there's no window.
1927 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1928 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1929 */
1930TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1932 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001933 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001934
1935 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1936 NotifyMotionArgs args;
1937
1938 // Touch down on the empty space
1939 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1940
1941 mDispatcher->waitForIdle();
1942 window->assertNoEvents();
1943
1944 // Now touch down on the window with another pointer
1945 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1946 mDispatcher->waitForIdle();
1947 window->consumeMotionDown();
1948}
1949
1950/**
1951 * Same test as above, but instead of touching the empty space, the first touch goes to
1952 * non-touchable window.
1953 */
1954TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1956 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001957 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001958 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1959 window1->setTouchable(false);
1960 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001961 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001962 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1963
1964 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1965
1966 NotifyMotionArgs args;
1967 // Touch down on the non-touchable window
1968 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1969
1970 mDispatcher->waitForIdle();
1971 window1->assertNoEvents();
1972 window2->assertNoEvents();
1973
1974 // Now touch down on the window with another pointer
1975 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1976 mDispatcher->waitForIdle();
1977 window2->consumeMotionDown();
1978}
1979
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001980/**
1981 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
1982 * to the event time of the first ACTION_DOWN sent to the particular window.
1983 */
1984TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
1985 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1986 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001987 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001988 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1989 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001990 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001991 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1992
1993 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1994
1995 NotifyMotionArgs args;
1996 // Touch down on the first window
1997 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1998
1999 mDispatcher->waitForIdle();
2000 InputEvent* inputEvent1 = window1->consume();
2001 window2->assertNoEvents();
2002 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2003 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2004 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2005
2006 // Now touch down on the window with another pointer
2007 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2008 mDispatcher->waitForIdle();
2009 InputEvent* inputEvent2 = window2->consume();
2010 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2011 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2012 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2013 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2014
2015 // Now move the pointer on the second window
2016 mDispatcher->notifyMotion(
2017 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2018 mDispatcher->waitForIdle();
2019 InputEvent* inputEvent3 = window2->consume();
2020 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
2021 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
2022
2023 // Now add new touch down on the second window
2024 mDispatcher->notifyMotion(
2025 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2026 mDispatcher->waitForIdle();
2027 InputEvent* inputEvent4 = window2->consume();
2028 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
2029 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
2030
2031 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2032 window1->consumeMotionMove();
2033 window1->assertNoEvents();
2034
2035 // Now move the pointer on the first window
2036 mDispatcher->notifyMotion(
2037 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2038 mDispatcher->waitForIdle();
2039 InputEvent* inputEvent5 = window1->consume();
2040 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2041 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2042
2043 mDispatcher->notifyMotion(&(
2044 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2045 mDispatcher->waitForIdle();
2046 InputEvent* inputEvent6 = window1->consume();
2047 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2048 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2049}
2050
Garfield Tandf26e862020-07-01 20:18:19 -07002051TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002052 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002053 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002054 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002055 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002056 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002057 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002058 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002059
2060 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2061
2062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2063
2064 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002066 injectMotionEvent(mDispatcher,
2067 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2068 AINPUT_SOURCE_MOUSE)
2069 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2070 .x(900)
2071 .y(400))
2072 .build()));
2073 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2074 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2075 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2076 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2077
2078 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002080 injectMotionEvent(mDispatcher,
2081 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2082 AINPUT_SOURCE_MOUSE)
2083 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2084 .x(300)
2085 .y(400))
2086 .build()));
2087 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2088 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2089 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2090 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2091 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2092 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2093
2094 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002096 injectMotionEvent(mDispatcher,
2097 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2098 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2099 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2100 .x(300)
2101 .y(400))
2102 .build()));
2103 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2104
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002106 injectMotionEvent(mDispatcher,
2107 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2108 AINPUT_SOURCE_MOUSE)
2109 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2110 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2111 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2112 .x(300)
2113 .y(400))
2114 .build()));
2115 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2116 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2117
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002119 injectMotionEvent(mDispatcher,
2120 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2121 AINPUT_SOURCE_MOUSE)
2122 .buttonState(0)
2123 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2124 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2125 .x(300)
2126 .y(400))
2127 .build()));
2128 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2129 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2130
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002132 injectMotionEvent(mDispatcher,
2133 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2134 .buttonState(0)
2135 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2136 .x(300)
2137 .y(400))
2138 .build()));
2139 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2140
2141 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002143 injectMotionEvent(mDispatcher,
2144 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2145 AINPUT_SOURCE_MOUSE)
2146 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2147 .x(900)
2148 .y(400))
2149 .build()));
2150 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2151 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2152 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2153 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2154 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2155 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2156}
2157
2158// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2159// directly in this test.
2160TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002162 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002163 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002164 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002165
2166 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2167
2168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2169
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002171 injectMotionEvent(mDispatcher,
2172 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2173 AINPUT_SOURCE_MOUSE)
2174 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2175 .x(300)
2176 .y(400))
2177 .build()));
2178 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2179 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2180
2181 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002183 injectMotionEvent(mDispatcher,
2184 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2185 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2186 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2187 .x(300)
2188 .y(400))
2189 .build()));
2190 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2191
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002193 injectMotionEvent(mDispatcher,
2194 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2195 AINPUT_SOURCE_MOUSE)
2196 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2197 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2198 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2199 .x(300)
2200 .y(400))
2201 .build()));
2202 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2203 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002206 injectMotionEvent(mDispatcher,
2207 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2208 AINPUT_SOURCE_MOUSE)
2209 .buttonState(0)
2210 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2211 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2212 .x(300)
2213 .y(400))
2214 .build()));
2215 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2216 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2217
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002219 injectMotionEvent(mDispatcher,
2220 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2221 .buttonState(0)
2222 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2223 .x(300)
2224 .y(400))
2225 .build()));
2226 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2227
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002229 injectMotionEvent(mDispatcher,
2230 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2231 AINPUT_SOURCE_MOUSE)
2232 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2233 .x(300)
2234 .y(400))
2235 .build()));
2236 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2237 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2238}
2239
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002240/**
2241 * Inject a mouse hover event followed by a tap from touchscreen.
2242 * In the current implementation, the tap does not cause a HOVER_EXIT event.
2243 */
2244TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2246 sp<FakeWindowHandle> window =
2247 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2248 window->setFrame(Rect(0, 0, 100, 100));
2249
2250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2251
2252 // Inject a hover_move from mouse.
2253 NotifyMotionArgs motionArgs =
2254 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2255 ADISPLAY_ID_DEFAULT, {{50, 50}});
2256 motionArgs.xCursorPosition = 50;
2257 motionArgs.yCursorPosition = 50;
2258 mDispatcher->notifyMotion(&motionArgs);
2259 ASSERT_NO_FATAL_FAILURE(
2260 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2261 WithSource(AINPUT_SOURCE_MOUSE))));
2262 ASSERT_NO_FATAL_FAILURE(
2263 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2264 WithSource(AINPUT_SOURCE_MOUSE))));
2265
2266 // Tap on the window
2267 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2268 ADISPLAY_ID_DEFAULT, {{10, 10}});
2269 mDispatcher->notifyMotion(&motionArgs);
2270 ASSERT_NO_FATAL_FAILURE(
2271 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2272 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2273
2274 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2275 ADISPLAY_ID_DEFAULT, {{10, 10}});
2276 mDispatcher->notifyMotion(&motionArgs);
2277 ASSERT_NO_FATAL_FAILURE(
2278 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2279 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2280}
2281
Garfield Tan00f511d2019-06-12 16:55:40 -07002282TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002284
2285 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002286 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002287 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002288 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002289 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002290 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002291
2292 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2293
Arthur Hung72d8dc32020-03-28 00:48:39 +00002294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002295
2296 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2297 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002299 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002300 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002301 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002302 windowRight->assertNoEvents();
2303}
2304
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002305TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002306 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002307 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2308 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002309 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002310
Arthur Hung72d8dc32020-03-28 00:48:39 +00002311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002312 setFocusedWindow(window);
2313
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002314 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002315
2316 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2317 mDispatcher->notifyKey(&keyArgs);
2318
2319 // Window should receive key down event.
2320 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2321
2322 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2323 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002324 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002325 mDispatcher->notifyDeviceReset(&args);
2326 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2327 AKEY_EVENT_FLAG_CANCELED);
2328}
2329
2330TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002331 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002332 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2333 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002334
Arthur Hung72d8dc32020-03-28 00:48:39 +00002335 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002336
2337 NotifyMotionArgs motionArgs =
2338 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2339 ADISPLAY_ID_DEFAULT);
2340 mDispatcher->notifyMotion(&motionArgs);
2341
2342 // Window should receive motion down event.
2343 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2344
2345 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2346 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002347 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002348 mDispatcher->notifyDeviceReset(&args);
2349 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2350 0 /*expectedFlags*/);
2351}
2352
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002353TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2354 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002355 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2356 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002357 window->setFocusable(true);
2358
2359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2360 setFocusedWindow(window);
2361
2362 window->consumeFocusEvent(true);
2363
2364 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2365 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2366 const nsecs_t injectTime = keyArgs.eventTime;
2367 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2368 mDispatcher->notifyKey(&keyArgs);
2369 // The dispatching time should be always greater than or equal to intercept key timeout.
2370 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2371 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2372 std::chrono::nanoseconds(interceptKeyTimeout).count());
2373}
2374
2375TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002377 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2378 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002379 window->setFocusable(true);
2380
2381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2382 setFocusedWindow(window);
2383
2384 window->consumeFocusEvent(true);
2385
2386 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2387 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2388 mFakePolicy->setInterceptKeyTimeout(150ms);
2389 mDispatcher->notifyKey(&keyDown);
2390 mDispatcher->notifyKey(&keyUp);
2391
2392 // Window should receive key event immediately when same key up.
2393 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2394 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2395}
2396
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002397/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002398 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2399 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2400 * ACTION_OUTSIDE event is sent per gesture.
2401 */
2402TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2403 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2404 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002405 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2406 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002407 window->setWatchOutsideTouch(true);
2408 window->setFrame(Rect{0, 0, 100, 100});
2409 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002410 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2411 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002412 secondWindow->setFrame(Rect{100, 100, 200, 200});
2413 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002414 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2415 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002416 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2418
2419 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2420 NotifyMotionArgs motionArgs =
2421 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2422 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2423 mDispatcher->notifyMotion(&motionArgs);
2424 window->assertNoEvents();
2425 secondWindow->assertNoEvents();
2426
2427 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2428 // Now, `window` should get ACTION_OUTSIDE.
2429 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2430 {PointF{-10, -10}, PointF{105, 105}});
2431 mDispatcher->notifyMotion(&motionArgs);
2432 window->consumeMotionOutside();
2433 secondWindow->consumeMotionDown();
2434 thirdWindow->assertNoEvents();
2435
2436 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2437 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2438 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2439 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2440 mDispatcher->notifyMotion(&motionArgs);
2441 window->assertNoEvents();
2442 secondWindow->consumeMotionMove();
2443 thirdWindow->consumeMotionDown();
2444}
2445
Prabir Pradhan814fe082022-07-22 20:22:18 +00002446TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2447 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002448 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2449 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002450 window->setFocusable(true);
2451
2452 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2453 setFocusedWindow(window);
2454
2455 window->consumeFocusEvent(true);
2456
2457 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2458 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2459 mDispatcher->notifyKey(&keyDown);
2460 mDispatcher->notifyKey(&keyUp);
2461
2462 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2463 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2464
2465 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2466 mDispatcher->onWindowInfosChanged({}, {});
2467
2468 window->consumeFocusEvent(false);
2469
2470 mDispatcher->notifyKey(&keyDown);
2471 mDispatcher->notifyKey(&keyUp);
2472 window->assertNoEvents();
2473}
2474
Arthur Hung96483742022-11-15 03:30:48 +00002475TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2476 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2477 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2478 "Fake Window", ADISPLAY_ID_DEFAULT);
2479 // Ensure window is non-split and have some transform.
2480 window->setPreventSplitting(true);
2481 window->setWindowOffset(20, 40);
2482 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2483
2484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2486 {50, 50}))
2487 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2488 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2489
2490 const MotionEvent secondFingerDownEvent =
2491 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2492 .displayId(ADISPLAY_ID_DEFAULT)
2493 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2494 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2495 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2496 .x(-30)
2497 .y(-50))
2498 .build();
2499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2500 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2501 InputEventInjectionSync::WAIT_FOR_RESULT))
2502 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2503
2504 const MotionEvent* event = window->consumeMotion();
2505 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2506 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2507 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2508 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2509 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2510}
2511
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002512/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002513 * Ensure the correct coordinate spaces are used by InputDispatcher.
2514 *
2515 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2516 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2517 * space.
2518 */
2519class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2520public:
2521 void SetUp() override {
2522 InputDispatcherTest::SetUp();
2523 mDisplayInfos.clear();
2524 mWindowInfos.clear();
2525 }
2526
2527 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2528 gui::DisplayInfo info;
2529 info.displayId = displayId;
2530 info.transform = transform;
2531 mDisplayInfos.push_back(std::move(info));
2532 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2533 }
2534
2535 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2536 mWindowInfos.push_back(*windowHandle->getInfo());
2537 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2538 }
2539
2540 // Set up a test scenario where the display has a scaled projection and there are two windows
2541 // on the display.
2542 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2543 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2544 // respectively.
2545 ui::Transform displayTransform;
2546 displayTransform.set(2, 0, 0, 4);
2547 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2548
2549 std::shared_ptr<FakeApplicationHandle> application =
2550 std::make_shared<FakeApplicationHandle>();
2551
2552 // Add two windows to the display. Their frames are represented in the display space.
2553 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002554 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2555 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002556 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2557 addWindow(firstWindow);
2558
2559 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002560 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2561 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002562 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2563 addWindow(secondWindow);
2564 return {std::move(firstWindow), std::move(secondWindow)};
2565 }
2566
2567private:
2568 std::vector<gui::DisplayInfo> mDisplayInfos;
2569 std::vector<gui::WindowInfo> mWindowInfos;
2570};
2571
2572TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2573 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2574 // Send down to the first window. The point is represented in the display space. The point is
2575 // selected so that if the hit test was done with the transform applied to it, then it would
2576 // end up in the incorrect window.
2577 NotifyMotionArgs downMotionArgs =
2578 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2579 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2580 mDispatcher->notifyMotion(&downMotionArgs);
2581
2582 firstWindow->consumeMotionDown();
2583 secondWindow->assertNoEvents();
2584}
2585
2586// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2587// the event should be treated as being in the logical display space.
2588TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2589 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2590 // Send down to the first window. The point is represented in the logical display space. The
2591 // point is selected so that if the hit test was done in logical display space, then it would
2592 // end up in the incorrect window.
2593 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2594 PointF{75 * 2, 55 * 4});
2595
2596 firstWindow->consumeMotionDown();
2597 secondWindow->assertNoEvents();
2598}
2599
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002600// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2601// event should be treated as being in the logical display space.
2602TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2603 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2604
2605 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2606 ui::Transform injectedEventTransform;
2607 injectedEventTransform.set(matrix);
2608 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2609 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2610
2611 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2612 .displayId(ADISPLAY_ID_DEFAULT)
2613 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2614 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2615 .x(untransformedPoint.x)
2616 .y(untransformedPoint.y))
2617 .build();
2618 event.transform(matrix);
2619
2620 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2621 InputEventInjectionSync::WAIT_FOR_RESULT);
2622
2623 firstWindow->consumeMotionDown();
2624 secondWindow->assertNoEvents();
2625}
2626
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002627TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2628 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2629
2630 // Send down to the second window.
2631 NotifyMotionArgs downMotionArgs =
2632 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2633 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2634 mDispatcher->notifyMotion(&downMotionArgs);
2635
2636 firstWindow->assertNoEvents();
2637 const MotionEvent* event = secondWindow->consumeMotion();
2638 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2639
2640 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2641 EXPECT_EQ(300, event->getRawX(0));
2642 EXPECT_EQ(880, event->getRawY(0));
2643
2644 // Ensure that the x and y values are in the window's coordinate space.
2645 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2646 // the logical display space. This will be the origin of the window space.
2647 EXPECT_EQ(100, event->getX(0));
2648 EXPECT_EQ(80, event->getY(0));
2649}
2650
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002651using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2652 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002653
2654class TransferTouchFixture : public InputDispatcherTest,
2655 public ::testing::WithParamInterface<TransferFunction> {};
2656
2657TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002658 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002659
2660 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002661 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002662 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2663 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002664 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002665 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2666 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002667
2668 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002670
2671 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002672 NotifyMotionArgs downMotionArgs =
2673 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2674 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002675 mDispatcher->notifyMotion(&downMotionArgs);
2676 // Only the first window should get the down event
2677 firstWindow->consumeMotionDown();
2678 secondWindow->assertNoEvents();
2679
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002680 // Transfer touch to the second window
2681 TransferFunction f = GetParam();
2682 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2683 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002684 // The first window gets cancel and the second gets down
2685 firstWindow->consumeMotionCancel();
2686 secondWindow->consumeMotionDown();
2687
2688 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002689 NotifyMotionArgs upMotionArgs =
2690 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2691 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002692 mDispatcher->notifyMotion(&upMotionArgs);
2693 // The first window gets no events and the second gets up
2694 firstWindow->assertNoEvents();
2695 secondWindow->consumeMotionUp();
2696}
2697
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002698/**
2699 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2700 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2701 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2702 * natural to the user.
2703 * In this test, we are sending a pointer to both spy window and first window. We then try to
2704 * transfer touch to the second window. The dispatcher should identify the first window as the
2705 * one that should lose the gesture, and therefore the action should be to move the gesture from
2706 * the first window to the second.
2707 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2708 * the other API, as well.
2709 */
2710TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2712
2713 // Create a couple of windows + a spy window
2714 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002715 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002716 spyWindow->setTrustedOverlay(true);
2717 spyWindow->setSpy(true);
2718 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002719 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002720 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002721 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002722
2723 // Add the windows to the dispatcher
2724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2725
2726 // Send down to the first window
2727 NotifyMotionArgs downMotionArgs =
2728 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2729 ADISPLAY_ID_DEFAULT);
2730 mDispatcher->notifyMotion(&downMotionArgs);
2731 // Only the first window and spy should get the down event
2732 spyWindow->consumeMotionDown();
2733 firstWindow->consumeMotionDown();
2734
2735 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2736 // if f === 'transferTouch'.
2737 TransferFunction f = GetParam();
2738 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2739 ASSERT_TRUE(success);
2740 // The first window gets cancel and the second gets down
2741 firstWindow->consumeMotionCancel();
2742 secondWindow->consumeMotionDown();
2743
2744 // Send up event to the second window
2745 NotifyMotionArgs upMotionArgs =
2746 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2747 ADISPLAY_ID_DEFAULT);
2748 mDispatcher->notifyMotion(&upMotionArgs);
2749 // The first window gets no events and the second+spy get up
2750 firstWindow->assertNoEvents();
2751 spyWindow->consumeMotionUp();
2752 secondWindow->consumeMotionUp();
2753}
2754
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002755TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002756 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002757
2758 PointF touchPoint = {10, 10};
2759
2760 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002761 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002762 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2763 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002764 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002765 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002766 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2767 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002768 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002769
2770 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002772
2773 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002774 NotifyMotionArgs downMotionArgs =
2775 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2776 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002777 mDispatcher->notifyMotion(&downMotionArgs);
2778 // Only the first window should get the down event
2779 firstWindow->consumeMotionDown();
2780 secondWindow->assertNoEvents();
2781
2782 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002783 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002784 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002785 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002786 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2787 // Only the first window should get the pointer down event
2788 firstWindow->consumeMotionPointerDown(1);
2789 secondWindow->assertNoEvents();
2790
2791 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002792 TransferFunction f = GetParam();
2793 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2794 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002795 // The first window gets cancel and the second gets down and pointer down
2796 firstWindow->consumeMotionCancel();
2797 secondWindow->consumeMotionDown();
2798 secondWindow->consumeMotionPointerDown(1);
2799
2800 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002801 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002802 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002803 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002804 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2805 // The first window gets nothing and the second gets pointer up
2806 firstWindow->assertNoEvents();
2807 secondWindow->consumeMotionPointerUp(1);
2808
2809 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002810 NotifyMotionArgs upMotionArgs =
2811 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2812 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002813 mDispatcher->notifyMotion(&upMotionArgs);
2814 // The first window gets nothing and the second gets up
2815 firstWindow->assertNoEvents();
2816 secondWindow->consumeMotionUp();
2817}
2818
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002819// For the cases of single pointer touch and two pointers non-split touch, the api's
2820// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2821// for the case where there are multiple pointers split across several windows.
2822INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2823 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002824 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2825 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002826 return dispatcher->transferTouch(destChannelToken,
2827 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002828 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002829 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2830 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002831 return dispatcher->transferTouchFocus(from, to,
2832 false /*isDragAndDrop*/);
2833 }));
2834
Svet Ganov5d3bc372020-01-26 23:11:07 -08002835TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002836 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002837
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002838 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002839 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2840 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002841 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002842
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002843 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002844 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2845 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002846 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002847
2848 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002850
2851 PointF pointInFirst = {300, 200};
2852 PointF pointInSecond = {300, 600};
2853
2854 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002855 NotifyMotionArgs firstDownMotionArgs =
2856 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2857 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002858 mDispatcher->notifyMotion(&firstDownMotionArgs);
2859 // Only the first window should get the down event
2860 firstWindow->consumeMotionDown();
2861 secondWindow->assertNoEvents();
2862
2863 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002864 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002865 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002866 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002867 mDispatcher->notifyMotion(&secondDownMotionArgs);
2868 // The first window gets a move and the second a down
2869 firstWindow->consumeMotionMove();
2870 secondWindow->consumeMotionDown();
2871
2872 // Transfer touch focus to the second window
2873 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2874 // The first window gets cancel and the new gets pointer down (it already saw down)
2875 firstWindow->consumeMotionCancel();
2876 secondWindow->consumeMotionPointerDown(1);
2877
2878 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002879 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002880 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002881 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002882 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2883 // The first window gets nothing and the second gets pointer up
2884 firstWindow->assertNoEvents();
2885 secondWindow->consumeMotionPointerUp(1);
2886
2887 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002888 NotifyMotionArgs upMotionArgs =
2889 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2890 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002891 mDispatcher->notifyMotion(&upMotionArgs);
2892 // The first window gets nothing and the second gets up
2893 firstWindow->assertNoEvents();
2894 secondWindow->consumeMotionUp();
2895}
2896
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002897// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2898// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2899// touch is not supported, so the touch should continue on those windows and the transferred-to
2900// window should get nothing.
2901TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2902 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2903
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002904 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002905 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2906 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002907 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002908
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002909 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002910 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2911 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002912 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002913
2914 // Add the windows to the dispatcher
2915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2916
2917 PointF pointInFirst = {300, 200};
2918 PointF pointInSecond = {300, 600};
2919
2920 // Send down to the first window
2921 NotifyMotionArgs firstDownMotionArgs =
2922 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2923 ADISPLAY_ID_DEFAULT, {pointInFirst});
2924 mDispatcher->notifyMotion(&firstDownMotionArgs);
2925 // Only the first window should get the down event
2926 firstWindow->consumeMotionDown();
2927 secondWindow->assertNoEvents();
2928
2929 // Send down to the second window
2930 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002931 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002932 {pointInFirst, pointInSecond});
2933 mDispatcher->notifyMotion(&secondDownMotionArgs);
2934 // The first window gets a move and the second a down
2935 firstWindow->consumeMotionMove();
2936 secondWindow->consumeMotionDown();
2937
2938 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002939 const bool transferred =
2940 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002941 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2942 ASSERT_FALSE(transferred);
2943 firstWindow->assertNoEvents();
2944 secondWindow->assertNoEvents();
2945
2946 // The rest of the dispatch should proceed as normal
2947 // Send pointer up to the second window
2948 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002949 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002950 {pointInFirst, pointInSecond});
2951 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2952 // The first window gets MOVE and the second gets pointer up
2953 firstWindow->consumeMotionMove();
2954 secondWindow->consumeMotionUp();
2955
2956 // Send up event to the first window
2957 NotifyMotionArgs upMotionArgs =
2958 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2959 ADISPLAY_ID_DEFAULT);
2960 mDispatcher->notifyMotion(&upMotionArgs);
2961 // The first window gets nothing and the second gets up
2962 firstWindow->consumeMotionUp();
2963 secondWindow->assertNoEvents();
2964}
2965
Arthur Hungabbb9d82021-09-01 14:52:30 +00002966// This case will create two windows and one mirrored window on the default display and mirror
2967// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2968// the windows info of second display before default display.
2969TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2970 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2971 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002972 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002973 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002974 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002975 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002976 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002977
2978 sp<FakeWindowHandle> mirrorWindowInPrimary =
2979 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2980 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002981
2982 sp<FakeWindowHandle> firstWindowInSecondary =
2983 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2984 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002985
2986 sp<FakeWindowHandle> secondWindowInSecondary =
2987 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2988 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002989
2990 // Update window info, let it find window handle of second display first.
2991 mDispatcher->setInputWindows(
2992 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2993 {ADISPLAY_ID_DEFAULT,
2994 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2995
2996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2998 {50, 50}))
2999 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3000
3001 // Window should receive motion event.
3002 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3003
3004 // Transfer touch focus
3005 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3006 secondWindowInPrimary->getToken()));
3007 // The first window gets cancel.
3008 firstWindowInPrimary->consumeMotionCancel();
3009 secondWindowInPrimary->consumeMotionDown();
3010
3011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3012 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3013 ADISPLAY_ID_DEFAULT, {150, 50}))
3014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3015 firstWindowInPrimary->assertNoEvents();
3016 secondWindowInPrimary->consumeMotionMove();
3017
3018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3019 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3020 {150, 50}))
3021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3022 firstWindowInPrimary->assertNoEvents();
3023 secondWindowInPrimary->consumeMotionUp();
3024}
3025
3026// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3027// 'transferTouch' api.
3028TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3029 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3030 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003031 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003032 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003033 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003034 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003035 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003036
3037 sp<FakeWindowHandle> mirrorWindowInPrimary =
3038 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3039 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003040
3041 sp<FakeWindowHandle> firstWindowInSecondary =
3042 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3043 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003044
3045 sp<FakeWindowHandle> secondWindowInSecondary =
3046 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3047 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003048
3049 // Update window info, let it find window handle of second display first.
3050 mDispatcher->setInputWindows(
3051 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3052 {ADISPLAY_ID_DEFAULT,
3053 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3054
3055 // Touch on second display.
3056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3059
3060 // Window should receive motion event.
3061 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3062
3063 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003064 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003065
3066 // The first window gets cancel.
3067 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3068 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3069
3070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3071 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3072 SECOND_DISPLAY_ID, {150, 50}))
3073 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3074 firstWindowInPrimary->assertNoEvents();
3075 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3076
3077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3078 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3080 firstWindowInPrimary->assertNoEvents();
3081 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3082}
3083
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003084TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003085 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003086 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3087 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003088
Vishnu Nair47074b82020-08-14 11:54:47 -07003089 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003091 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092
3093 window->consumeFocusEvent(true);
3094
3095 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3096 mDispatcher->notifyKey(&keyArgs);
3097
3098 // Window should receive key down event.
3099 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3100}
3101
3102TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003103 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003104 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3105 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003106
Arthur Hung72d8dc32020-03-28 00:48:39 +00003107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003108
3109 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3110 mDispatcher->notifyKey(&keyArgs);
3111 mDispatcher->waitForIdle();
3112
3113 window->assertNoEvents();
3114}
3115
3116// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3117TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003118 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003119 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3120 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003121
Arthur Hung72d8dc32020-03-28 00:48:39 +00003122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123
3124 // Send key
3125 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3126 mDispatcher->notifyKey(&keyArgs);
3127 // Send motion
3128 NotifyMotionArgs motionArgs =
3129 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3130 ADISPLAY_ID_DEFAULT);
3131 mDispatcher->notifyMotion(&motionArgs);
3132
3133 // Window should receive only the motion event
3134 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3135 window->assertNoEvents(); // Key event or focus event will not be received
3136}
3137
arthurhungea3f4fc2020-12-21 23:18:53 +08003138TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3139 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3140
arthurhungea3f4fc2020-12-21 23:18:53 +08003141 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003142 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3143 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003144 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003145
arthurhungea3f4fc2020-12-21 23:18:53 +08003146 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003147 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3148 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003149 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003150
3151 // Add the windows to the dispatcher
3152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3153
3154 PointF pointInFirst = {300, 200};
3155 PointF pointInSecond = {300, 600};
3156
3157 // Send down to the first window
3158 NotifyMotionArgs firstDownMotionArgs =
3159 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3160 ADISPLAY_ID_DEFAULT, {pointInFirst});
3161 mDispatcher->notifyMotion(&firstDownMotionArgs);
3162 // Only the first window should get the down event
3163 firstWindow->consumeMotionDown();
3164 secondWindow->assertNoEvents();
3165
3166 // Send down to the second window
3167 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003168 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003169 {pointInFirst, pointInSecond});
3170 mDispatcher->notifyMotion(&secondDownMotionArgs);
3171 // The first window gets a move and the second a down
3172 firstWindow->consumeMotionMove();
3173 secondWindow->consumeMotionDown();
3174
3175 // Send pointer cancel to the second window
3176 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003177 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003178 {pointInFirst, pointInSecond});
3179 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3180 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3181 // The first window gets move and the second gets cancel.
3182 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3183 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3184
3185 // Send up event.
3186 NotifyMotionArgs upMotionArgs =
3187 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3188 ADISPLAY_ID_DEFAULT);
3189 mDispatcher->notifyMotion(&upMotionArgs);
3190 // The first window gets up and the second gets nothing.
3191 firstWindow->consumeMotionUp();
3192 secondWindow->assertNoEvents();
3193}
3194
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003195TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3196 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3197
3198 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003199 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3201 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3202 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3203 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3204
3205 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3206 window->assertNoEvents();
3207 mDispatcher->waitForIdle();
3208}
3209
chaviwd1c23182019-12-20 18:44:56 -08003210class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003211public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003212 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003213 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003214 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003215 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003216 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003217 }
3218
chaviwd1c23182019-12-20 18:44:56 -08003219 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3220
3221 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3222 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3223 expectedDisplayId, expectedFlags);
3224 }
3225
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003226 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3227
3228 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3229
chaviwd1c23182019-12-20 18:44:56 -08003230 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3231 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3232 expectedDisplayId, expectedFlags);
3233 }
3234
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003235 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3236 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3237 expectedDisplayId, expectedFlags);
3238 }
3239
chaviwd1c23182019-12-20 18:44:56 -08003240 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3241 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3242 expectedDisplayId, expectedFlags);
3243 }
3244
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003245 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3246 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3247 expectedDisplayId, expectedFlags);
3248 }
3249
Arthur Hungfbfa5722021-11-16 02:45:54 +00003250 void consumeMotionPointerDown(int32_t pointerIdx) {
3251 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3252 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3253 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3254 0 /*expectedFlags*/);
3255 }
3256
Evan Rosky84f07f02021-04-16 10:42:42 -07003257 MotionEvent* consumeMotion() {
3258 InputEvent* event = mInputReceiver->consume();
3259 if (!event) {
3260 ADD_FAILURE() << "No event was produced";
3261 return nullptr;
3262 }
3263 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3264 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3265 return nullptr;
3266 }
3267 return static_cast<MotionEvent*>(event);
3268 }
3269
chaviwd1c23182019-12-20 18:44:56 -08003270 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3271
3272private:
3273 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003274};
3275
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003276using InputDispatcherMonitorTest = InputDispatcherTest;
3277
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003278/**
3279 * Two entities that receive touch: A window, and a global monitor.
3280 * The touch goes to the window, and then the window disappears.
3281 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3282 * for the monitor, as well.
3283 * 1. foregroundWindow
3284 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3285 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003286TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003287 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3288 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003289 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003290
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003291 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003292
3293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3295 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3296 {100, 200}))
3297 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3298
3299 // Both the foreground window and the global monitor should receive the touch down
3300 window->consumeMotionDown();
3301 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3302
3303 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3304 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3305 ADISPLAY_ID_DEFAULT, {110, 200}))
3306 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3307
3308 window->consumeMotionMove();
3309 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3310
3311 // Now the foreground window goes away
3312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3313 window->consumeMotionCancel();
3314 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3315
3316 // If more events come in, there will be no more foreground window to send them to. This will
3317 // cause a cancel for the monitor, as well.
3318 ASSERT_EQ(InputEventInjectionResult::FAILED,
3319 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3320 ADISPLAY_ID_DEFAULT, {120, 200}))
3321 << "Injection should fail because the window was removed";
3322 window->assertNoEvents();
3323 // Global monitor now gets the cancel
3324 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3325}
3326
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003327TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003329 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3330 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003332
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003333 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003334
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003336 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003337 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003338 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003339 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003340}
3341
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003342TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3343 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003344
Chris Yea209fde2020-07-22 13:54:51 -07003345 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003346 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3347 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003349
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003351 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003352 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003353 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003354 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003355
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003356 // Pilfer pointers from the monitor.
3357 // This should not do anything and the window should continue to receive events.
3358 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003359
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003361 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3362 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003364
3365 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3366 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003367}
3368
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003369TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003371 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3372 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3374 window->setWindowOffset(20, 40);
3375 window->setWindowTransform(0, 1, -1, 0);
3376
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003377 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003378
3379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3382 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3383 MotionEvent* event = monitor.consumeMotion();
3384 // Even though window has transform, gesture monitor must not.
3385 ASSERT_EQ(ui::Transform(), event->getTransform());
3386}
3387
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003388TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003389 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003390 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003391
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003392 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003394 << "Injection should fail if there is a monitor, but no touchable window";
3395 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003396}
3397
chaviw81e2bb92019-12-18 15:03:51 -08003398TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003399 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003400 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3401 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003402
Arthur Hung72d8dc32020-03-28 00:48:39 +00003403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003404
3405 NotifyMotionArgs motionArgs =
3406 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3407 ADISPLAY_ID_DEFAULT);
3408
3409 mDispatcher->notifyMotion(&motionArgs);
3410 // Window should receive motion down event.
3411 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3412
3413 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003414 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003415 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3416 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3417 motionArgs.pointerCoords[0].getX() - 10);
3418
3419 mDispatcher->notifyMotion(&motionArgs);
3420 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3421 0 /*expectedFlags*/);
3422}
3423
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003424/**
3425 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3426 * the device default right away. In the test scenario, we check both the default value,
3427 * and the action of enabling / disabling.
3428 */
3429TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003430 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003431 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3432 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003433 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003434
3435 // Set focused application.
3436 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003437 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003438
3439 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003441 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003442 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3443
3444 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003445 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003447 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3448
3449 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003450 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003451 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003452 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003453 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003455 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003456 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3457
3458 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003459 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003461 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3462
3463 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003464 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003465 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003466 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003467 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003468 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003469 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003470 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3471
3472 window->assertNoEvents();
3473}
3474
Gang Wange9087892020-01-07 12:17:14 -05003475TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003476 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003477 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3478 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003479
3480 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003481 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003482
Arthur Hung72d8dc32020-03-28 00:48:39 +00003483 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003484 setFocusedWindow(window);
3485
Gang Wange9087892020-01-07 12:17:14 -05003486 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3487
3488 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3489 mDispatcher->notifyKey(&keyArgs);
3490
3491 InputEvent* event = window->consume();
3492 ASSERT_NE(event, nullptr);
3493
3494 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3495 ASSERT_NE(verified, nullptr);
3496 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3497
3498 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3499 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3500 ASSERT_EQ(keyArgs.source, verified->source);
3501 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3502
3503 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3504
3505 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003506 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003507 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003508 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3509 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3510 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3511 ASSERT_EQ(0, verifiedKey.repeatCount);
3512}
3513
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003514TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003515 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003516 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3517 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003518
3519 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3520
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003521 ui::Transform transform;
3522 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3523
3524 gui::DisplayInfo displayInfo;
3525 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3526 displayInfo.transform = transform;
3527
3528 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003529
3530 NotifyMotionArgs motionArgs =
3531 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3532 ADISPLAY_ID_DEFAULT);
3533 mDispatcher->notifyMotion(&motionArgs);
3534
3535 InputEvent* event = window->consume();
3536 ASSERT_NE(event, nullptr);
3537
3538 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3539 ASSERT_NE(verified, nullptr);
3540 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3541
3542 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3543 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3544 EXPECT_EQ(motionArgs.source, verified->source);
3545 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3546
3547 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3548
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003549 const vec2 rawXY =
3550 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3551 motionArgs.pointerCoords[0].getXYValue());
3552 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3553 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003554 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003555 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003556 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003557 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3558 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3559}
3560
chaviw09c8d2d2020-08-24 15:48:26 -07003561/**
3562 * Ensure that separate calls to sign the same data are generating the same key.
3563 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3564 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3565 * tests.
3566 */
3567TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3568 KeyEvent event = getTestKeyEvent();
3569 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3570
3571 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3572 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3573 ASSERT_EQ(hmac1, hmac2);
3574}
3575
3576/**
3577 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3578 */
3579TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3580 KeyEvent event = getTestKeyEvent();
3581 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3582 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3583
3584 verifiedEvent.deviceId += 1;
3585 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3586
3587 verifiedEvent.source += 1;
3588 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3589
3590 verifiedEvent.eventTimeNanos += 1;
3591 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3592
3593 verifiedEvent.displayId += 1;
3594 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3595
3596 verifiedEvent.action += 1;
3597 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3598
3599 verifiedEvent.downTimeNanos += 1;
3600 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3601
3602 verifiedEvent.flags += 1;
3603 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3604
3605 verifiedEvent.keyCode += 1;
3606 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3607
3608 verifiedEvent.scanCode += 1;
3609 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3610
3611 verifiedEvent.metaState += 1;
3612 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3613
3614 verifiedEvent.repeatCount += 1;
3615 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3616}
3617
Vishnu Nair958da932020-08-21 17:12:37 -07003618TEST_F(InputDispatcherTest, SetFocusedWindow) {
3619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3620 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003621 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003622 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003623 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003624 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3625
3626 // Top window is also focusable but is not granted focus.
3627 windowTop->setFocusable(true);
3628 windowSecond->setFocusable(true);
3629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3630 setFocusedWindow(windowSecond);
3631
3632 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3634 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003635
3636 // Focused window should receive event.
3637 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3638 windowTop->assertNoEvents();
3639}
3640
3641TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3642 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3643 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003644 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003645 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3646
3647 window->setFocusable(true);
3648 // Release channel for window is no longer valid.
3649 window->releaseChannel();
3650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3651 setFocusedWindow(window);
3652
3653 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003654 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3655 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003656
3657 // window channel is invalid, so it should not receive any input event.
3658 window->assertNoEvents();
3659}
3660
3661TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3662 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3663 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003664 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003665 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003666 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3667
Vishnu Nair958da932020-08-21 17:12:37 -07003668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3669 setFocusedWindow(window);
3670
3671 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003672 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3673 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003674
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003675 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003676 window->assertNoEvents();
3677}
3678
3679TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3681 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003682 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003683 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003684 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003685 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3686
3687 windowTop->setFocusable(true);
3688 windowSecond->setFocusable(true);
3689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3690 setFocusedWindow(windowTop);
3691 windowTop->consumeFocusEvent(true);
3692
3693 setFocusedWindow(windowSecond, windowTop);
3694 windowSecond->consumeFocusEvent(true);
3695 windowTop->consumeFocusEvent(false);
3696
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3698 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003699
3700 // Focused window should receive event.
3701 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3702}
3703
3704TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3705 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3706 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003707 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003708 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003709 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003710 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3711
3712 windowTop->setFocusable(true);
3713 windowSecond->setFocusable(true);
3714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3715 setFocusedWindow(windowSecond, windowTop);
3716
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003717 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3718 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003719
3720 // Event should be dropped.
3721 windowTop->assertNoEvents();
3722 windowSecond->assertNoEvents();
3723}
3724
3725TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3726 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3727 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003728 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003729 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003730 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3731 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003732 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3733
3734 window->setFocusable(true);
3735 previousFocusedWindow->setFocusable(true);
3736 window->setVisible(false);
3737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3738 setFocusedWindow(previousFocusedWindow);
3739 previousFocusedWindow->consumeFocusEvent(true);
3740
3741 // Requesting focus on invisible window takes focus from currently focused window.
3742 setFocusedWindow(window);
3743 previousFocusedWindow->consumeFocusEvent(false);
3744
3745 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003747 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003748 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003749
3750 // Window does not get focus event or key down.
3751 window->assertNoEvents();
3752
3753 // Window becomes visible.
3754 window->setVisible(true);
3755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3756
3757 // Window receives focus event.
3758 window->consumeFocusEvent(true);
3759 // Focused window receives key down.
3760 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3761}
3762
Vishnu Nair599f1412021-06-21 10:39:58 -07003763TEST_F(InputDispatcherTest, DisplayRemoved) {
3764 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3765 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003766 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003767 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3768
3769 // window is granted focus.
3770 window->setFocusable(true);
3771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3772 setFocusedWindow(window);
3773 window->consumeFocusEvent(true);
3774
3775 // When a display is removed window loses focus.
3776 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3777 window->consumeFocusEvent(false);
3778}
3779
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003780/**
3781 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3782 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3783 * of the 'slipperyEnterWindow'.
3784 *
3785 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3786 * a way so that the touched location is no longer covered by the top window.
3787 *
3788 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3789 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3790 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3791 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3792 * with ACTION_DOWN).
3793 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3794 * window moved itself away from the touched location and had Flag::SLIPPERY.
3795 *
3796 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3797 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3798 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3799 *
3800 * In this test, we ensure that the event received by the bottom window has
3801 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3802 */
3803TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003804 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3805 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003806
3807 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3808 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3809
3810 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003811 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003812 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003813 // Make sure this one overlaps the bottom window
3814 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3815 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3816 // one. Windows with the same owner are not considered to be occluding each other.
3817 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3818
3819 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003820 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003821 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3822
3823 mDispatcher->setInputWindows(
3824 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3825
3826 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3827 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3828 ADISPLAY_ID_DEFAULT, {{50, 50}});
3829 mDispatcher->notifyMotion(&args);
3830 slipperyExitWindow->consumeMotionDown();
3831 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3832 mDispatcher->setInputWindows(
3833 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3834
3835 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3836 ADISPLAY_ID_DEFAULT, {{51, 51}});
3837 mDispatcher->notifyMotion(&args);
3838
3839 slipperyExitWindow->consumeMotionCancel();
3840
3841 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3842 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3843}
3844
Garfield Tan1c7bc862020-01-28 13:24:04 -08003845class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3846protected:
3847 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3848 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3849
Chris Yea209fde2020-07-22 13:54:51 -07003850 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003851 sp<FakeWindowHandle> mWindow;
3852
3853 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003854 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003855 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003856 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003857 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3858 ASSERT_EQ(OK, mDispatcher->start());
3859
3860 setUpWindow();
3861 }
3862
3863 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003864 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003865 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003866
Vishnu Nair47074b82020-08-14 11:54:47 -07003867 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003869 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003870 mWindow->consumeFocusEvent(true);
3871 }
3872
Chris Ye2ad95392020-09-01 13:44:44 -07003873 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003874 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003875 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003876 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3877 mDispatcher->notifyKey(&keyArgs);
3878
3879 // Window should receive key down event.
3880 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3881 }
3882
3883 void expectKeyRepeatOnce(int32_t repeatCount) {
3884 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3885 InputEvent* repeatEvent = mWindow->consume();
3886 ASSERT_NE(nullptr, repeatEvent);
3887
3888 uint32_t eventType = repeatEvent->getType();
3889 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3890
3891 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3892 uint32_t eventAction = repeatKeyEvent->getAction();
3893 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3894 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3895 }
3896
Chris Ye2ad95392020-09-01 13:44:44 -07003897 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003898 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003899 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003900 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3901 mDispatcher->notifyKey(&keyArgs);
3902
3903 // Window should receive key down event.
3904 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3905 0 /*expectedFlags*/);
3906 }
3907};
3908
3909TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003910 sendAndConsumeKeyDown(1 /* deviceId */);
3911 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3912 expectKeyRepeatOnce(repeatCount);
3913 }
3914}
3915
3916TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3917 sendAndConsumeKeyDown(1 /* deviceId */);
3918 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3919 expectKeyRepeatOnce(repeatCount);
3920 }
3921 sendAndConsumeKeyDown(2 /* deviceId */);
3922 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003923 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3924 expectKeyRepeatOnce(repeatCount);
3925 }
3926}
3927
3928TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003929 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003930 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003931 sendAndConsumeKeyUp(1 /* deviceId */);
3932 mWindow->assertNoEvents();
3933}
3934
3935TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3936 sendAndConsumeKeyDown(1 /* deviceId */);
3937 expectKeyRepeatOnce(1 /*repeatCount*/);
3938 sendAndConsumeKeyDown(2 /* deviceId */);
3939 expectKeyRepeatOnce(1 /*repeatCount*/);
3940 // Stale key up from device 1.
3941 sendAndConsumeKeyUp(1 /* deviceId */);
3942 // Device 2 is still down, keep repeating
3943 expectKeyRepeatOnce(2 /*repeatCount*/);
3944 expectKeyRepeatOnce(3 /*repeatCount*/);
3945 // Device 2 key up
3946 sendAndConsumeKeyUp(2 /* deviceId */);
3947 mWindow->assertNoEvents();
3948}
3949
3950TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3951 sendAndConsumeKeyDown(1 /* deviceId */);
3952 expectKeyRepeatOnce(1 /*repeatCount*/);
3953 sendAndConsumeKeyDown(2 /* deviceId */);
3954 expectKeyRepeatOnce(1 /*repeatCount*/);
3955 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3956 sendAndConsumeKeyUp(2 /* deviceId */);
3957 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003958 mWindow->assertNoEvents();
3959}
3960
liushenxiang42232912021-05-21 20:24:09 +08003961TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3962 sendAndConsumeKeyDown(DEVICE_ID);
3963 expectKeyRepeatOnce(1 /*repeatCount*/);
3964 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3965 mDispatcher->notifyDeviceReset(&args);
3966 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3967 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3968 mWindow->assertNoEvents();
3969}
3970
Garfield Tan1c7bc862020-01-28 13:24:04 -08003971TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003972 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003973 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3974 InputEvent* repeatEvent = mWindow->consume();
3975 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3976 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3977 IdGenerator::getSource(repeatEvent->getId()));
3978 }
3979}
3980
3981TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003982 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003983
3984 std::unordered_set<int32_t> idSet;
3985 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3986 InputEvent* repeatEvent = mWindow->consume();
3987 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3988 int32_t id = repeatEvent->getId();
3989 EXPECT_EQ(idSet.end(), idSet.find(id));
3990 idSet.insert(id);
3991 }
3992}
3993
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003994/* Test InputDispatcher for MultiDisplay */
3995class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3996public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003997 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003998 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003999
Chris Yea209fde2020-07-22 13:54:51 -07004000 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004001 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004002 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004003
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004004 // Set focus window for primary display, but focused display would be second one.
4005 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004006 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004008 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004009 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004010
Chris Yea209fde2020-07-22 13:54:51 -07004011 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004012 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004013 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004014 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004015 // Set focus display to second one.
4016 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4017 // Set focus window for second display.
4018 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004019 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004020 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004021 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004022 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004023 }
4024
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004025 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004026 InputDispatcherTest::TearDown();
4027
Chris Yea209fde2020-07-22 13:54:51 -07004028 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004029 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004030 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004031 windowInSecondary.clear();
4032 }
4033
4034protected:
Chris Yea209fde2020-07-22 13:54:51 -07004035 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004036 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004037 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004038 sp<FakeWindowHandle> windowInSecondary;
4039};
4040
4041TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4042 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4044 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4045 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004046 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004047 windowInSecondary->assertNoEvents();
4048
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004049 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4051 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004053 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004054 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004055}
4056
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004057TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004058 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4060 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004062 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004063 windowInSecondary->assertNoEvents();
4064
4065 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004067 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004068 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004069 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004070
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004071 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004072 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004073
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004074 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004075 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4076 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004077
4078 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004079 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004080 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004081 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004082 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004083 windowInSecondary->assertNoEvents();
4084}
4085
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004086// Test per-display input monitors for motion event.
4087TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004088 FakeMonitorReceiver monitorInPrimary =
4089 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4090 FakeMonitorReceiver monitorInSecondary =
4091 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004092
4093 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4095 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004097 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004098 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004099 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004100 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004101
4102 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4104 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4105 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004106 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004107 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004108 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004109 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004110
4111 // Test inject a non-pointer motion event.
4112 // If specific a display, it will dispatch to the focused window of particular display,
4113 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004117 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004118 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004119 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004120 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004121}
4122
4123// Test per-display input monitors for key event.
4124TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004125 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004126 FakeMonitorReceiver monitorInPrimary =
4127 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4128 FakeMonitorReceiver monitorInSecondary =
4129 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004130
4131 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4133 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004134 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004135 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004136 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004137 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004138}
4139
Vishnu Nair958da932020-08-21 17:12:37 -07004140TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4141 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004142 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004143 secondWindowInPrimary->setFocusable(true);
4144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4145 setFocusedWindow(secondWindowInPrimary);
4146 windowInPrimary->consumeFocusEvent(false);
4147 secondWindowInPrimary->consumeFocusEvent(true);
4148
4149 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4151 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004152 windowInPrimary->assertNoEvents();
4153 windowInSecondary->assertNoEvents();
4154 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4155}
4156
Arthur Hungdfd528e2021-12-08 13:23:04 +00004157TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4158 FakeMonitorReceiver monitorInPrimary =
4159 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4160 FakeMonitorReceiver monitorInSecondary =
4161 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4162
4163 // Test touch down on primary display.
4164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4165 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4166 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4167 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4168 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4169
4170 // Test touch down on second display.
4171 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4172 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4173 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4174 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4175 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4176
4177 // Trigger cancel touch.
4178 mDispatcher->cancelCurrentTouch();
4179 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4180 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4181 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4182 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4183
4184 // Test inject a move motion event, no window/monitor should receive the event.
4185 ASSERT_EQ(InputEventInjectionResult::FAILED,
4186 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4187 ADISPLAY_ID_DEFAULT, {110, 200}))
4188 << "Inject motion event should return InputEventInjectionResult::FAILED";
4189 windowInPrimary->assertNoEvents();
4190 monitorInPrimary.assertNoEvents();
4191
4192 ASSERT_EQ(InputEventInjectionResult::FAILED,
4193 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4194 SECOND_DISPLAY_ID, {110, 200}))
4195 << "Inject motion event should return InputEventInjectionResult::FAILED";
4196 windowInSecondary->assertNoEvents();
4197 monitorInSecondary.assertNoEvents();
4198}
4199
Jackal Guof9696682018-10-05 12:23:23 +08004200class InputFilterTest : public InputDispatcherTest {
4201protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004202 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4203 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004204 NotifyMotionArgs motionArgs;
4205
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004206 motionArgs =
4207 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004208 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004209 motionArgs =
4210 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004211 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004212 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004213 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004214 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4215 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004216 } else {
4217 mFakePolicy->assertFilterInputEventWasNotCalled();
4218 }
4219 }
4220
4221 void testNotifyKey(bool expectToBeFiltered) {
4222 NotifyKeyArgs keyArgs;
4223
4224 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4225 mDispatcher->notifyKey(&keyArgs);
4226 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4227 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004228 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004229
4230 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004231 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004232 } else {
4233 mFakePolicy->assertFilterInputEventWasNotCalled();
4234 }
4235 }
4236};
4237
4238// Test InputFilter for MotionEvent
4239TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4240 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4241 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4242 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4243
4244 // Enable InputFilter
4245 mDispatcher->setInputFilterEnabled(true);
4246 // Test touch on both primary and second display, and check if both events are filtered.
4247 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4248 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4249
4250 // Disable InputFilter
4251 mDispatcher->setInputFilterEnabled(false);
4252 // Test touch on both primary and second display, and check if both events aren't filtered.
4253 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4254 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4255}
4256
4257// Test InputFilter for KeyEvent
4258TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4259 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4260 testNotifyKey(/*expectToBeFiltered*/ false);
4261
4262 // Enable InputFilter
4263 mDispatcher->setInputFilterEnabled(true);
4264 // Send a key event, and check if it is filtered.
4265 testNotifyKey(/*expectToBeFiltered*/ true);
4266
4267 // Disable InputFilter
4268 mDispatcher->setInputFilterEnabled(false);
4269 // Send a key event, and check if it isn't filtered.
4270 testNotifyKey(/*expectToBeFiltered*/ false);
4271}
4272
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004273// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4274// logical display coordinate space.
4275TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4276 ui::Transform firstDisplayTransform;
4277 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4278 ui::Transform secondDisplayTransform;
4279 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4280
4281 std::vector<gui::DisplayInfo> displayInfos(2);
4282 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4283 displayInfos[0].transform = firstDisplayTransform;
4284 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4285 displayInfos[1].transform = secondDisplayTransform;
4286
4287 mDispatcher->onWindowInfosChanged({}, displayInfos);
4288
4289 // Enable InputFilter
4290 mDispatcher->setInputFilterEnabled(true);
4291
4292 // Ensure the correct transforms are used for the displays.
4293 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4294 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4295}
4296
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004297class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4298protected:
4299 virtual void SetUp() override {
4300 InputDispatcherTest::SetUp();
4301
4302 /**
4303 * We don't need to enable input filter to test the injected event policy, but we enabled it
4304 * here to make the tests more realistic, since this policy only matters when inputfilter is
4305 * on.
4306 */
4307 mDispatcher->setInputFilterEnabled(true);
4308
4309 std::shared_ptr<InputApplicationHandle> application =
4310 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004311 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4312 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004313
4314 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4315 mWindow->setFocusable(true);
4316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4317 setFocusedWindow(mWindow);
4318 mWindow->consumeFocusEvent(true);
4319 }
4320
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004321 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4322 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004323 KeyEvent event;
4324
4325 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4326 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4327 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4328 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4329 const int32_t additionalPolicyFlags =
4330 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004332 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004333 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4334 policyFlags | additionalPolicyFlags));
4335
4336 InputEvent* received = mWindow->consume();
4337 ASSERT_NE(nullptr, received);
4338 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004339 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4340 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4341 ASSERT_EQ(flags, keyEvent.getFlags());
4342 }
4343
4344 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4345 int32_t flags) {
4346 MotionEvent event;
4347 PointerProperties pointerProperties[1];
4348 PointerCoords pointerCoords[1];
4349 pointerProperties[0].clear();
4350 pointerProperties[0].id = 0;
4351 pointerCoords[0].clear();
4352 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4353 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4354
4355 ui::Transform identityTransform;
4356 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4357 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4358 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4359 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4360 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004361 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004362 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004363 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4364
4365 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004367 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004368 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4369 policyFlags | additionalPolicyFlags));
4370
4371 InputEvent* received = mWindow->consume();
4372 ASSERT_NE(nullptr, received);
4373 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4374 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4375 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4376 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004377 }
4378
4379private:
4380 sp<FakeWindowHandle> mWindow;
4381};
4382
4383TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004384 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4385 // filter. Without it, the event will no different from a regularly injected event, and the
4386 // injected device id will be overwritten.
4387 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4388 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004389}
4390
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004391TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004392 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004393 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4394 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4395}
4396
4397TEST_F(InputFilterInjectionPolicyTest,
4398 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4399 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4400 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4401 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004402}
4403
4404TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4405 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004406 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004407}
4408
chaviwfd6d3512019-03-25 13:23:49 -07004409class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004410 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004411 InputDispatcherTest::SetUp();
4412
Chris Yea209fde2020-07-22 13:54:51 -07004413 std::shared_ptr<FakeApplicationHandle> application =
4414 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004415 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004416 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004417 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004418
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004419 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004420 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004421 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004422
4423 // Set focused application.
4424 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004425 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004426
4427 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004428 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004429 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004430 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004431 }
4432
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004433 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004434 InputDispatcherTest::TearDown();
4435
4436 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004437 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004438 }
4439
4440protected:
4441 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004442 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004443 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004444};
4445
4446// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4447// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4448// the onPointerDownOutsideFocus callback.
4449TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4452 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004454 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004455
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004456 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004457 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4458}
4459
4460// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4461// DOWN on the window that doesn't have focus. Ensure no window received the
4462// onPointerDownOutsideFocus callback.
4463TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004465 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004466 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004467 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004468
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004469 ASSERT_TRUE(mDispatcher->waitForIdle());
4470 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004471}
4472
4473// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4474// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4475TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4477 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004478 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004479 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004480
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004481 ASSERT_TRUE(mDispatcher->waitForIdle());
4482 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004483}
4484
4485// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4486// DOWN on the window that already has focus. Ensure no window received the
4487// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004488TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004490 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004491 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004493 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004494
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004495 ASSERT_TRUE(mDispatcher->waitForIdle());
4496 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004497}
4498
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004499// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4500// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4501TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4502 const MotionEvent event =
4503 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4504 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4505 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4506 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4507 .build();
4508 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4510 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4511
4512 ASSERT_TRUE(mDispatcher->waitForIdle());
4513 mFakePolicy->assertOnPointerDownWasNotCalled();
4514 // Ensure that the unfocused window did not receive any FOCUS events.
4515 mUnfocusedWindow->assertNoEvents();
4516}
4517
chaviwaf87b3e2019-10-01 16:59:28 -07004518// These tests ensures we can send touch events to a single client when there are multiple input
4519// windows that point to the same client token.
4520class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4521 virtual void SetUp() override {
4522 InputDispatcherTest::SetUp();
4523
Chris Yea209fde2020-07-22 13:54:51 -07004524 std::shared_ptr<FakeApplicationHandle> application =
4525 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004526 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4527 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004528 mWindow1->setFrame(Rect(0, 0, 100, 100));
4529
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004530 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4531 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004532 mWindow2->setFrame(Rect(100, 100, 200, 200));
4533
Arthur Hung72d8dc32020-03-28 00:48:39 +00004534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004535 }
4536
4537protected:
4538 sp<FakeWindowHandle> mWindow1;
4539 sp<FakeWindowHandle> mWindow2;
4540
4541 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004542 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004543 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4544 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004545 }
4546
4547 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4548 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004549 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004550 InputEvent* event = window->consume();
4551
4552 ASSERT_NE(nullptr, event) << name.c_str()
4553 << ": consumer should have returned non-NULL event.";
4554
4555 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4556 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4557 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4558
4559 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004560 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004561
4562 for (size_t i = 0; i < points.size(); i++) {
4563 float expectedX = points[i].x;
4564 float expectedY = points[i].y;
4565
4566 EXPECT_EQ(expectedX, motionEvent.getX(i))
4567 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4568 << ", got " << motionEvent.getX(i);
4569 EXPECT_EQ(expectedY, motionEvent.getY(i))
4570 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4571 << ", got " << motionEvent.getY(i);
4572 }
4573 }
chaviw9eaa22c2020-07-01 16:21:27 -07004574
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004575 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004576 std::vector<PointF> expectedPoints) {
4577 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4578 ADISPLAY_ID_DEFAULT, touchedPoints);
4579 mDispatcher->notifyMotion(&motionArgs);
4580
4581 // Always consume from window1 since it's the window that has the InputReceiver
4582 consumeMotionEvent(mWindow1, action, expectedPoints);
4583 }
chaviwaf87b3e2019-10-01 16:59:28 -07004584};
4585
4586TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4587 // Touch Window 1
4588 PointF touchedPoint = {10, 10};
4589 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004590 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004591
4592 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004593 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004594
4595 // Touch Window 2
4596 touchedPoint = {150, 150};
4597 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004598 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004599}
4600
chaviw9eaa22c2020-07-01 16:21:27 -07004601TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4602 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004603 mWindow2->setWindowScale(0.5f, 0.5f);
4604
4605 // Touch Window 1
4606 PointF touchedPoint = {10, 10};
4607 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004608 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004609 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004610 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004611
4612 // Touch Window 2
4613 touchedPoint = {150, 150};
4614 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004615 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4616 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004617
chaviw9eaa22c2020-07-01 16:21:27 -07004618 // Update the transform so rotation is set
4619 mWindow2->setWindowTransform(0, -1, 1, 0);
4620 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4621 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004622}
4623
chaviw9eaa22c2020-07-01 16:21:27 -07004624TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004625 mWindow2->setWindowScale(0.5f, 0.5f);
4626
4627 // Touch Window 1
4628 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4629 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004630 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004631
4632 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004633 touchedPoints.push_back(PointF{150, 150});
4634 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004635 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004636
chaviw9eaa22c2020-07-01 16:21:27 -07004637 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004638 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004639 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004640
chaviw9eaa22c2020-07-01 16:21:27 -07004641 // Update the transform so rotation is set for Window 2
4642 mWindow2->setWindowTransform(0, -1, 1, 0);
4643 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004644 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004645}
4646
chaviw9eaa22c2020-07-01 16:21:27 -07004647TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004648 mWindow2->setWindowScale(0.5f, 0.5f);
4649
4650 // Touch Window 1
4651 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4652 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004653 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004654
4655 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004656 touchedPoints.push_back(PointF{150, 150});
4657 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004658
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004659 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004660
4661 // Move both windows
4662 touchedPoints = {{20, 20}, {175, 175}};
4663 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4664 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4665
chaviw9eaa22c2020-07-01 16:21:27 -07004666 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004667
chaviw9eaa22c2020-07-01 16:21:27 -07004668 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004669 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004670 expectedPoints.pop_back();
4671
4672 // Touch Window 2
4673 mWindow2->setWindowTransform(0, -1, 1, 0);
4674 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004675 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004676
4677 // Move both windows
4678 touchedPoints = {{20, 20}, {175, 175}};
4679 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4680 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4681
4682 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004683}
4684
4685TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4686 mWindow1->setWindowScale(0.5f, 0.5f);
4687
4688 // Touch Window 1
4689 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4690 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004691 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004692
4693 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004694 touchedPoints.push_back(PointF{150, 150});
4695 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004696
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004697 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004698
4699 // Move both windows
4700 touchedPoints = {{20, 20}, {175, 175}};
4701 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4702 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4703
chaviw9eaa22c2020-07-01 16:21:27 -07004704 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004705}
4706
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004707class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4708 virtual void SetUp() override {
4709 InputDispatcherTest::SetUp();
4710
Chris Yea209fde2020-07-22 13:54:51 -07004711 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004712 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004713 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4714 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004715 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004716 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004717 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004718
4719 // Set focused application.
4720 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4721
4722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004723 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004724 mWindow->consumeFocusEvent(true);
4725 }
4726
4727 virtual void TearDown() override {
4728 InputDispatcherTest::TearDown();
4729 mWindow.clear();
4730 }
4731
4732protected:
Chris Yea209fde2020-07-22 13:54:51 -07004733 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004734 sp<FakeWindowHandle> mWindow;
4735 static constexpr PointF WINDOW_LOCATION = {20, 20};
4736
4737 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004739 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4740 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004742 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4743 WINDOW_LOCATION));
4744 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004745
4746 sp<FakeWindowHandle> addSpyWindow() {
4747 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004748 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004749 spy->setTrustedOverlay(true);
4750 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004751 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004752 spy->setDispatchingTimeout(30ms);
4753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4754 return spy;
4755 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004756};
4757
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758// Send a tap and respond, which should not cause an ANR.
4759TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4760 tapOnWindow();
4761 mWindow->consumeMotionDown();
4762 mWindow->consumeMotionUp();
4763 ASSERT_TRUE(mDispatcher->waitForIdle());
4764 mFakePolicy->assertNotifyAnrWasNotCalled();
4765}
4766
4767// Send a regular key and respond, which should not cause an ANR.
4768TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4771 ASSERT_TRUE(mDispatcher->waitForIdle());
4772 mFakePolicy->assertNotifyAnrWasNotCalled();
4773}
4774
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004775TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4776 mWindow->setFocusable(false);
4777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4778 mWindow->consumeFocusEvent(false);
4779
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004780 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004781 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004782 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4783 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004785 // Key will not go to window because we have no focused window.
4786 // The 'no focused window' ANR timer should start instead.
4787
4788 // Now, the focused application goes away.
4789 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4790 // The key should get dropped and there should be no ANR.
4791
4792 ASSERT_TRUE(mDispatcher->waitForIdle());
4793 mFakePolicy->assertNotifyAnrWasNotCalled();
4794}
4795
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004796// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4798// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004799TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004801 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4802 WINDOW_LOCATION));
4803
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004804 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4805 ASSERT_TRUE(sequenceNum);
4806 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004807 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809 mWindow->finishEvent(*sequenceNum);
4810 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4811 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004812 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004813 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004814}
4815
4816// Send a key to the app and have the app not respond right away.
4817TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4818 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004820 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4821 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004822 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004823 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004824 ASSERT_TRUE(mDispatcher->waitForIdle());
4825}
4826
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004827// We have a focused application, but no focused window
4828TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004829 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4831 mWindow->consumeFocusEvent(false);
4832
4833 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4836 WINDOW_LOCATION));
4837 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4838 mDispatcher->waitForIdle();
4839 mFakePolicy->assertNotifyAnrWasNotCalled();
4840
4841 // Once a focused event arrives, we get an ANR for this application
4842 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4843 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004845 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004846 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07004849 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850 ASSERT_TRUE(mDispatcher->waitForIdle());
4851}
4852
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004853/**
4854 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4855 * there will not be an ANR.
4856 */
4857TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4858 mWindow->setFocusable(false);
4859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4860 mWindow->consumeFocusEvent(false);
4861
4862 KeyEvent event;
4863 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4864 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4865
4866 // Define a valid key down event that is stale (too old).
4867 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4868 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4869 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4870
4871 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4872
4873 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004874 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004875 InputEventInjectionSync::WAIT_FOR_RESULT,
4876 INJECT_EVENT_TIMEOUT, policyFlags);
4877 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4878 << "Injection should fail because the event is stale";
4879
4880 ASSERT_TRUE(mDispatcher->waitForIdle());
4881 mFakePolicy->assertNotifyAnrWasNotCalled();
4882 mWindow->assertNoEvents();
4883}
4884
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004886// Make sure that we don't notify policy twice about the same ANR.
4887TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004888 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4890 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891
4892 // Once a focused event arrives, we get an ANR for this application
4893 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4894 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004897 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07004899 const std::chrono::duration appTimeout =
4900 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4901 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902
Vishnu Naire4df8752022-09-08 09:17:55 -07004903 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004904 // ANR should not be raised again. It is up to policy to do that if it desires.
4905 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004907 // If we now get a focused window, the ANR should stop, but the policy handles that via
4908 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004909 ASSERT_TRUE(mDispatcher->waitForIdle());
4910}
4911
4912// We have a focused application, but no focused window
4913TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004914 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4916 mWindow->consumeFocusEvent(false);
4917
4918 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004919 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004921 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4922 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923
Vishnu Naire4df8752022-09-08 09:17:55 -07004924 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4925 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926
4927 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004928 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929 ASSERT_TRUE(mDispatcher->waitForIdle());
4930 mWindow->assertNoEvents();
4931}
4932
4933/**
4934 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4935 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4936 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4937 * the ANR mechanism should still work.
4938 *
4939 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4940 * DOWN event, while not responding on the second one.
4941 */
4942TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4943 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4944 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4945 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4946 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4947 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004948 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004949
4950 // Now send ACTION_UP, with identical timestamp
4951 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4952 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4953 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4954 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956
4957 // We have now sent down and up. Let's consume first event and then ANR on the second.
4958 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4959 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004960 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004961}
4962
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004963// A spy window can receive an ANR
4964TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4965 sp<FakeWindowHandle> spy = addSpyWindow();
4966
4967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4968 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4969 WINDOW_LOCATION));
4970 mWindow->consumeMotionDown();
4971
4972 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4973 ASSERT_TRUE(sequenceNum);
4974 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004975 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004976
4977 spy->finishEvent(*sequenceNum);
4978 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4979 0 /*flags*/);
4980 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004981 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004982}
4983
4984// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004986TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4987 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4990 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004993
4994 // Stuck on the ACTION_UP
4995 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004996 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004997
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004998 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005000 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5001 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002
5003 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5004 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005005 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005006 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005007 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005008}
5009
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005010// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005011// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005012TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5013 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014
5015 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005016 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5017 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005018
5019 mWindow->consumeMotionDown();
5020 // Stuck on the ACTION_UP
5021 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005022 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005023
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005024 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005026 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5027 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028
5029 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5030 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005031 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005032 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005033 spy->assertNoEvents();
5034}
5035
5036TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5037 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5038
5039 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5040
5041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5042 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5043 WINDOW_LOCATION));
5044
5045 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5046 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5047 ASSERT_TRUE(consumeSeq);
5048
Prabir Pradhanedd96402022-02-15 01:46:16 -08005049 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005050
5051 monitor.finishEvent(*consumeSeq);
5052 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5053
5054 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005055 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005056}
5057
5058// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5059// process events, you don't get an anr. When the window later becomes unresponsive again, you
5060// get an ANR again.
5061// 1. tap -> block on ACTION_UP -> receive ANR
5062// 2. consume all pending events (= queue becomes healthy again)
5063// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5064TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5065 tapOnWindow();
5066
5067 mWindow->consumeMotionDown();
5068 // Block on ACTION_UP
5069 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005070 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005071 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5072 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005073 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005074 mWindow->assertNoEvents();
5075
5076 tapOnWindow();
5077 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005078 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005079 mWindow->consumeMotionUp();
5080
5081 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005082 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005083 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005084 mWindow->assertNoEvents();
5085}
5086
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005087// If a connection remains unresponsive for a while, make sure policy is only notified once about
5088// it.
5089TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5092 WINDOW_LOCATION));
5093
5094 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005095 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005097 // 'notifyConnectionUnresponsive' should only be called once per connection
5098 mFakePolicy->assertNotifyAnrWasNotCalled();
5099 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 mWindow->consumeMotionDown();
5101 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5102 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5103 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005104 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005105 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005106 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005107}
5108
5109/**
5110 * If a window is processing a motion event, and then a key event comes in, the key event should
5111 * not to to the focused window until the motion is processed.
5112 *
5113 * Warning!!!
5114 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5115 * and the injection timeout that we specify when injecting the key.
5116 * We must have the injection timeout (10ms) be smaller than
5117 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5118 *
5119 * If that value changes, this test should also change.
5120 */
5121TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5122 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5124
5125 tapOnWindow();
5126 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5127 ASSERT_TRUE(downSequenceNum);
5128 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5129 ASSERT_TRUE(upSequenceNum);
5130 // Don't finish the events yet, and send a key
5131 // Injection will "succeed" because we will eventually give up and send the key to the focused
5132 // window even if motions are still being processed. But because the injection timeout is short,
5133 // we will receive INJECTION_TIMED_OUT as the result.
5134
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005135 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005137 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5138 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005139 // Key will not be sent to the window, yet, because the window is still processing events
5140 // and the key remains pending, waiting for the touch events to be processed
5141 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5142 ASSERT_FALSE(keySequenceNum);
5143
5144 std::this_thread::sleep_for(500ms);
5145 // if we wait long enough though, dispatcher will give up, and still send the key
5146 // to the focused window, even though we have not yet finished the motion event
5147 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5148 mWindow->finishEvent(*downSequenceNum);
5149 mWindow->finishEvent(*upSequenceNum);
5150}
5151
5152/**
5153 * If a window is processing a motion event, and then a key event comes in, the key event should
5154 * not go to the focused window until the motion is processed.
5155 * If then a new motion comes in, then the pending key event should be going to the currently
5156 * focused window right away.
5157 */
5158TEST_F(InputDispatcherSingleWindowAnr,
5159 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5160 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5162
5163 tapOnWindow();
5164 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5165 ASSERT_TRUE(downSequenceNum);
5166 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5167 ASSERT_TRUE(upSequenceNum);
5168 // Don't finish the events yet, and send a key
5169 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005171 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005172 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005173 // At this point, key is still pending, and should not be sent to the application yet.
5174 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5175 ASSERT_FALSE(keySequenceNum);
5176
5177 // Now tap down again. It should cause the pending key to go to the focused window right away.
5178 tapOnWindow();
5179 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5180 // the other events yet. We can finish events in any order.
5181 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5182 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5183 mWindow->consumeMotionDown();
5184 mWindow->consumeMotionUp();
5185 mWindow->assertNoEvents();
5186}
5187
5188class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5189 virtual void SetUp() override {
5190 InputDispatcherTest::SetUp();
5191
Chris Yea209fde2020-07-22 13:54:51 -07005192 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005193 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005194 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5195 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005197 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005198 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005200 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5201 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005202 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005203 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005204
5205 // Set focused application.
5206 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005207 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005208
5209 // Expect one focus window exist in display.
5210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005211 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212 mFocusedWindow->consumeFocusEvent(true);
5213 }
5214
5215 virtual void TearDown() override {
5216 InputDispatcherTest::TearDown();
5217
5218 mUnfocusedWindow.clear();
5219 mFocusedWindow.clear();
5220 }
5221
5222protected:
Chris Yea209fde2020-07-22 13:54:51 -07005223 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005224 sp<FakeWindowHandle> mUnfocusedWindow;
5225 sp<FakeWindowHandle> mFocusedWindow;
5226 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5227 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5228 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5229
5230 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5231
5232 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5233
5234private:
5235 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5238 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005240 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5241 location));
5242 }
5243};
5244
5245// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5246// should be ANR'd first.
5247TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005249 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5250 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005251 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005252 mFocusedWindow->consumeMotionDown();
5253 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5254 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5255 // We consumed all events, so no ANR
5256 ASSERT_TRUE(mDispatcher->waitForIdle());
5257 mFakePolicy->assertNotifyAnrWasNotCalled();
5258
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005260 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5261 FOCUSED_WINDOW_LOCATION));
5262 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5263 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264
5265 const std::chrono::duration timeout =
5266 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005267 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005268 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5269 // sequence to make it consistent
5270 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005272 mFocusedWindow->consumeMotionDown();
5273 // This cancel is generated because the connection was unresponsive
5274 mFocusedWindow->consumeMotionCancel();
5275 mFocusedWindow->assertNoEvents();
5276 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005277 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005278 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5279 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005280 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005281}
5282
5283// If we have 2 windows with identical timeouts that are both unresponsive,
5284// it doesn't matter which order they should have ANR.
5285// But we should receive ANR for both.
5286TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5287 // Set the timeout for unfocused window to match the focused window
5288 mUnfocusedWindow->setDispatchingTimeout(10ms);
5289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5290
5291 tapOnFocusedWindow();
5292 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005293 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5294 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5295 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005296
5297 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005298 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5299 mFocusedWindow->getToken() == anrConnectionToken2);
5300 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5301 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005302
5303 ASSERT_TRUE(mDispatcher->waitForIdle());
5304 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005305
5306 mFocusedWindow->consumeMotionDown();
5307 mFocusedWindow->consumeMotionUp();
5308 mUnfocusedWindow->consumeMotionOutside();
5309
Prabir Pradhanedd96402022-02-15 01:46:16 -08005310 sp<IBinder> responsiveToken1, responsiveToken2;
5311 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5312 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005313
5314 // Both applications should be marked as responsive, in any order
5315 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5316 mFocusedWindow->getToken() == responsiveToken2);
5317 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5318 mUnfocusedWindow->getToken() == responsiveToken2);
5319 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320}
5321
5322// If a window is already not responding, the second tap on the same window should be ignored.
5323// We should also log an error to account for the dropped event (not tested here).
5324// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5325TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5326 tapOnFocusedWindow();
5327 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5328 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5329 // Receive the events, but don't respond
5330 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5331 ASSERT_TRUE(downEventSequenceNum);
5332 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5333 ASSERT_TRUE(upEventSequenceNum);
5334 const std::chrono::duration timeout =
5335 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005336 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337
5338 // Tap once again
5339 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005340 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5342 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005343 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005344 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5345 FOCUSED_WINDOW_LOCATION));
5346 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5347 // valid touch target
5348 mUnfocusedWindow->assertNoEvents();
5349
5350 // Consume the first tap
5351 mFocusedWindow->finishEvent(*downEventSequenceNum);
5352 mFocusedWindow->finishEvent(*upEventSequenceNum);
5353 ASSERT_TRUE(mDispatcher->waitForIdle());
5354 // The second tap did not go to the focused window
5355 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005356 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005357 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5358 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005359 mFakePolicy->assertNotifyAnrWasNotCalled();
5360}
5361
5362// If you tap outside of all windows, there will not be ANR
5363TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005364 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005365 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5366 LOCATION_OUTSIDE_ALL_WINDOWS));
5367 ASSERT_TRUE(mDispatcher->waitForIdle());
5368 mFakePolicy->assertNotifyAnrWasNotCalled();
5369}
5370
5371// Since the focused window is paused, tapping on it should not produce any events
5372TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5373 mFocusedWindow->setPaused(true);
5374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5375
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005376 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005377 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5378 FOCUSED_WINDOW_LOCATION));
5379
5380 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5381 ASSERT_TRUE(mDispatcher->waitForIdle());
5382 // Should not ANR because the window is paused, and touches shouldn't go to it
5383 mFakePolicy->assertNotifyAnrWasNotCalled();
5384
5385 mFocusedWindow->assertNoEvents();
5386 mUnfocusedWindow->assertNoEvents();
5387}
5388
5389/**
5390 * If a window is processing a motion event, and then a key event comes in, the key event should
5391 * not to to the focused window until the motion is processed.
5392 * If a different window becomes focused at this time, the key should go to that window instead.
5393 *
5394 * Warning!!!
5395 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5396 * and the injection timeout that we specify when injecting the key.
5397 * We must have the injection timeout (10ms) be smaller than
5398 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5399 *
5400 * If that value changes, this test should also change.
5401 */
5402TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5403 // Set a long ANR timeout to prevent it from triggering
5404 mFocusedWindow->setDispatchingTimeout(2s);
5405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5406
5407 tapOnUnfocusedWindow();
5408 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5409 ASSERT_TRUE(downSequenceNum);
5410 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5411 ASSERT_TRUE(upSequenceNum);
5412 // Don't finish the events yet, and send a key
5413 // Injection will succeed because we will eventually give up and send the key to the focused
5414 // window even if motions are still being processed.
5415
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005416 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005417 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005418 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005420 // Key will not be sent to the window, yet, because the window is still processing events
5421 // and the key remains pending, waiting for the touch events to be processed
5422 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5423 ASSERT_FALSE(keySequenceNum);
5424
5425 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005426 mFocusedWindow->setFocusable(false);
5427 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005428 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005429 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005430
5431 // Focus events should precede the key events
5432 mUnfocusedWindow->consumeFocusEvent(true);
5433 mFocusedWindow->consumeFocusEvent(false);
5434
5435 // Finish the tap events, which should unblock dispatcher
5436 mUnfocusedWindow->finishEvent(*downSequenceNum);
5437 mUnfocusedWindow->finishEvent(*upSequenceNum);
5438
5439 // Now that all queues are cleared and no backlog in the connections, the key event
5440 // can finally go to the newly focused "mUnfocusedWindow".
5441 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5442 mFocusedWindow->assertNoEvents();
5443 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005444 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005445}
5446
5447// When the touch stream is split across 2 windows, and one of them does not respond,
5448// then ANR should be raised and the touch should be canceled for the unresponsive window.
5449// The other window should not be affected by that.
5450TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5451 // Touch Window 1
5452 NotifyMotionArgs motionArgs =
5453 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5454 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5455 mDispatcher->notifyMotion(&motionArgs);
5456 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5457 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5458
5459 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005460 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5461 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005462 mDispatcher->notifyMotion(&motionArgs);
5463
5464 const std::chrono::duration timeout =
5465 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005466 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005467
5468 mUnfocusedWindow->consumeMotionDown();
5469 mFocusedWindow->consumeMotionDown();
5470 // Focused window may or may not receive ACTION_MOVE
5471 // But it should definitely receive ACTION_CANCEL due to the ANR
5472 InputEvent* event;
5473 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5474 ASSERT_TRUE(moveOrCancelSequenceNum);
5475 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5476 ASSERT_NE(nullptr, event);
5477 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5478 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5479 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5480 mFocusedWindow->consumeMotionCancel();
5481 } else {
5482 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5483 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005484 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005485 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5486 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005487
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 mUnfocusedWindow->assertNoEvents();
5489 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005490 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005491}
5492
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005493/**
5494 * If we have no focused window, and a key comes in, we start the ANR timer.
5495 * The focused application should add a focused window before the timer runs out to prevent ANR.
5496 *
5497 * If the user touches another application during this time, the key should be dropped.
5498 * Next, if a new focused window comes in, without toggling the focused application,
5499 * then no ANR should occur.
5500 *
5501 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5502 * but in some cases the policy may not update the focused application.
5503 */
5504TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5505 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5506 std::make_shared<FakeApplicationHandle>();
5507 focusedApplication->setDispatchingTimeout(60ms);
5508 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5509 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5510 mFocusedWindow->setFocusable(false);
5511
5512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5513 mFocusedWindow->consumeFocusEvent(false);
5514
5515 // Send a key. The ANR timer should start because there is no focused window.
5516 // 'focusedApplication' will get blamed if this timer completes.
5517 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005518 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005519 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005520 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5521 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005522 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005523
5524 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5525 // then the injected touches won't cause the focused event to get dropped.
5526 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5527 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5528 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5529 // For this test, it means that the key would get delivered to the window once it becomes
5530 // focused.
5531 std::this_thread::sleep_for(10ms);
5532
5533 // Touch unfocused window. This should force the pending key to get dropped.
5534 NotifyMotionArgs motionArgs =
5535 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5536 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5537 mDispatcher->notifyMotion(&motionArgs);
5538
5539 // We do not consume the motion right away, because that would require dispatcher to first
5540 // process (== drop) the key event, and by that time, ANR will be raised.
5541 // Set the focused window first.
5542 mFocusedWindow->setFocusable(true);
5543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5544 setFocusedWindow(mFocusedWindow);
5545 mFocusedWindow->consumeFocusEvent(true);
5546 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5547 // to another application. This could be a bug / behaviour in the policy.
5548
5549 mUnfocusedWindow->consumeMotionDown();
5550
5551 ASSERT_TRUE(mDispatcher->waitForIdle());
5552 // Should not ANR because we actually have a focused window. It was just added too slowly.
5553 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5554}
5555
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005556// These tests ensure we cannot send touch events to a window that's positioned behind a window
5557// that has feature NO_INPUT_CHANNEL.
5558// Layout:
5559// Top (closest to user)
5560// mNoInputWindow (above all windows)
5561// mBottomWindow
5562// Bottom (furthest from user)
5563class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5564 virtual void SetUp() override {
5565 InputDispatcherTest::SetUp();
5566
5567 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005568 mNoInputWindow =
5569 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5570 "Window without input channel", ADISPLAY_ID_DEFAULT,
5571 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005572 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005573 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5574 // It's perfectly valid for this window to not have an associated input channel
5575
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005576 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5577 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005578 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5579
5580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5581 }
5582
5583protected:
5584 std::shared_ptr<FakeApplicationHandle> mApplication;
5585 sp<FakeWindowHandle> mNoInputWindow;
5586 sp<FakeWindowHandle> mBottomWindow;
5587};
5588
5589TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5590 PointF touchedPoint = {10, 10};
5591
5592 NotifyMotionArgs motionArgs =
5593 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5594 ADISPLAY_ID_DEFAULT, {touchedPoint});
5595 mDispatcher->notifyMotion(&motionArgs);
5596
5597 mNoInputWindow->assertNoEvents();
5598 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5599 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5600 // and therefore should prevent mBottomWindow from receiving touches
5601 mBottomWindow->assertNoEvents();
5602}
5603
5604/**
5605 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5606 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5607 */
5608TEST_F(InputDispatcherMultiWindowOcclusionTests,
5609 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005610 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5611 "Window with input channel and NO_INPUT_CHANNEL",
5612 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005613
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005614 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005615 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5617
5618 PointF touchedPoint = {10, 10};
5619
5620 NotifyMotionArgs motionArgs =
5621 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5622 ADISPLAY_ID_DEFAULT, {touchedPoint});
5623 mDispatcher->notifyMotion(&motionArgs);
5624
5625 mNoInputWindow->assertNoEvents();
5626 mBottomWindow->assertNoEvents();
5627}
5628
Vishnu Nair958da932020-08-21 17:12:37 -07005629class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5630protected:
5631 std::shared_ptr<FakeApplicationHandle> mApp;
5632 sp<FakeWindowHandle> mWindow;
5633 sp<FakeWindowHandle> mMirror;
5634
5635 virtual void SetUp() override {
5636 InputDispatcherTest::SetUp();
5637 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005638 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5639 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5640 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005641 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5642 mWindow->setFocusable(true);
5643 mMirror->setFocusable(true);
5644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5645 }
5646};
5647
5648TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5649 // Request focus on a mirrored window
5650 setFocusedWindow(mMirror);
5651
5652 // window gets focused
5653 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5655 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005656 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5657}
5658
5659// A focused & mirrored window remains focused only if the window and its mirror are both
5660// focusable.
5661TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5662 setFocusedWindow(mMirror);
5663
5664 // window gets focused
5665 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5667 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005668 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5670 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005671 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5672
5673 mMirror->setFocusable(false);
5674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5675
5676 // window loses focus since one of the windows associated with the token in not focusable
5677 mWindow->consumeFocusEvent(false);
5678
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005679 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5680 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005681 mWindow->assertNoEvents();
5682}
5683
5684// A focused & mirrored window remains focused until the window and its mirror both become
5685// invisible.
5686TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5687 setFocusedWindow(mMirror);
5688
5689 // window gets focused
5690 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5692 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005693 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5695 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005696 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5697
5698 mMirror->setVisible(false);
5699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5700
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5702 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005703 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5705 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005706 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5707
5708 mWindow->setVisible(false);
5709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5710
5711 // window loses focus only after all windows associated with the token become invisible.
5712 mWindow->consumeFocusEvent(false);
5713
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005714 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5715 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005716 mWindow->assertNoEvents();
5717}
5718
5719// A focused & mirrored window remains focused until both windows are removed.
5720TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5721 setFocusedWindow(mMirror);
5722
5723 // window gets focused
5724 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5726 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005727 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5729 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005730 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5731
5732 // single window is removed but the window token remains focused
5733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5734
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5736 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005737 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5739 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005740 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5741
5742 // Both windows are removed
5743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5744 mWindow->consumeFocusEvent(false);
5745
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005746 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5747 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005748 mWindow->assertNoEvents();
5749}
5750
5751// Focus request can be pending until one window becomes visible.
5752TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5753 // Request focus on an invisible mirror.
5754 mWindow->setVisible(false);
5755 mMirror->setVisible(false);
5756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5757 setFocusedWindow(mMirror);
5758
5759 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005761 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005762 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005763
5764 mMirror->setVisible(true);
5765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5766
5767 // window gets focused
5768 mWindow->consumeFocusEvent(true);
5769 // window gets the pending key event
5770 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5771}
Prabir Pradhan99987712020-11-10 18:43:05 -08005772
5773class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5774protected:
5775 std::shared_ptr<FakeApplicationHandle> mApp;
5776 sp<FakeWindowHandle> mWindow;
5777 sp<FakeWindowHandle> mSecondWindow;
5778
5779 void SetUp() override {
5780 InputDispatcherTest::SetUp();
5781 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005782 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005783 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005784 mSecondWindow =
5785 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005786 mSecondWindow->setFocusable(true);
5787
5788 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5790
5791 setFocusedWindow(mWindow);
5792 mWindow->consumeFocusEvent(true);
5793 }
5794
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005795 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5796 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005797 mDispatcher->notifyPointerCaptureChanged(&args);
5798 }
5799
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005800 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5801 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005802 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005803 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5804 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005805 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005806 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005807 }
5808};
5809
5810TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5811 // Ensure that capture cannot be obtained for unfocused windows.
5812 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5813 mFakePolicy->assertSetPointerCaptureNotCalled();
5814 mSecondWindow->assertNoEvents();
5815
5816 // Ensure that capture can be enabled from the focus window.
5817 requestAndVerifyPointerCapture(mWindow, true);
5818
5819 // Ensure that capture cannot be disabled from a window that does not have capture.
5820 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5821 mFakePolicy->assertSetPointerCaptureNotCalled();
5822
5823 // Ensure that capture can be disabled from the window with capture.
5824 requestAndVerifyPointerCapture(mWindow, false);
5825}
5826
5827TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005828 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005829
5830 setFocusedWindow(mSecondWindow);
5831
5832 // Ensure that the capture disabled event was sent first.
5833 mWindow->consumeCaptureEvent(false);
5834 mWindow->consumeFocusEvent(false);
5835 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005836 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005837
5838 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005839 notifyPointerCaptureChanged({});
5840 notifyPointerCaptureChanged(request);
5841 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005842 mWindow->assertNoEvents();
5843 mSecondWindow->assertNoEvents();
5844 mFakePolicy->assertSetPointerCaptureNotCalled();
5845}
5846
5847TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005848 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005849
5850 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005851 notifyPointerCaptureChanged({});
5852 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005853
5854 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005855 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005856 mWindow->consumeCaptureEvent(false);
5857 mWindow->assertNoEvents();
5858}
5859
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005860TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5861 requestAndVerifyPointerCapture(mWindow, true);
5862
5863 // The first window loses focus.
5864 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005865 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005866 mWindow->consumeCaptureEvent(false);
5867
5868 // Request Pointer Capture from the second window before the notification from InputReader
5869 // arrives.
5870 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005871 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005872
5873 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005874 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005875
5876 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005877 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005878
5879 mSecondWindow->consumeFocusEvent(true);
5880 mSecondWindow->consumeCaptureEvent(true);
5881}
5882
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005883TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5884 // App repeatedly enables and disables capture.
5885 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5886 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5887 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5888 mFakePolicy->assertSetPointerCaptureCalled(false);
5889 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5890 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5891
5892 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5893 // first request is now stale, this should do nothing.
5894 notifyPointerCaptureChanged(firstRequest);
5895 mWindow->assertNoEvents();
5896
5897 // InputReader notifies that the second request was enabled.
5898 notifyPointerCaptureChanged(secondRequest);
5899 mWindow->consumeCaptureEvent(true);
5900}
5901
Prabir Pradhan7092e262022-05-03 16:51:09 +00005902TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5903 requestAndVerifyPointerCapture(mWindow, true);
5904
5905 // App toggles pointer capture off and on.
5906 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5907 mFakePolicy->assertSetPointerCaptureCalled(false);
5908
5909 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5910 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5911
5912 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5913 // preceding "disable" request.
5914 notifyPointerCaptureChanged(enableRequest);
5915
5916 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5917 // any notifications.
5918 mWindow->assertNoEvents();
5919}
5920
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005921class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5922protected:
5923 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005924
5925 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5926 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5927
5928 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5929 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5930
5931 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5932 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5933 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5934 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5935 MAXIMUM_OBSCURING_OPACITY);
5936
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005937 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005938 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005939 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005940
5941 sp<FakeWindowHandle> mTouchWindow;
5942
5943 virtual void SetUp() override {
5944 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005945 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005946 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5947 }
5948
5949 virtual void TearDown() override {
5950 InputDispatcherTest::TearDown();
5951 mTouchWindow.clear();
5952 }
5953
chaviw3277faf2021-05-19 16:45:23 -05005954 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5955 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005956 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005957 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005958 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005959 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005960 return window;
5961 }
5962
5963 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5964 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5965 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005966 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005967 // Generate an arbitrary PID based on the UID
5968 window->setOwnerInfo(1777 + (uid % 10000), uid);
5969 return window;
5970 }
5971
5972 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5973 NotifyMotionArgs args =
5974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5975 ADISPLAY_ID_DEFAULT, points);
5976 mDispatcher->notifyMotion(&args);
5977 }
5978};
5979
5980TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005981 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005982 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005984
5985 touch();
5986
5987 mTouchWindow->assertNoEvents();
5988}
5989
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005990TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005991 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5992 const sp<FakeWindowHandle>& w =
5993 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5995
5996 touch();
5997
5998 mTouchWindow->assertNoEvents();
5999}
6000
6001TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006002 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6003 const sp<FakeWindowHandle>& w =
6004 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6006
6007 touch();
6008
6009 w->assertNoEvents();
6010}
6011
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006012TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006013 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006015
6016 touch();
6017
6018 mTouchWindow->consumeAnyMotionDown();
6019}
6020
6021TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006022 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006023 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006024 w->setFrame(Rect(0, 0, 50, 50));
6025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006026
6027 touch({PointF{100, 100}});
6028
6029 mTouchWindow->consumeAnyMotionDown();
6030}
6031
6032TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006033 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006034 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6036
6037 touch();
6038
6039 mTouchWindow->consumeAnyMotionDown();
6040}
6041
6042TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6043 const sp<FakeWindowHandle>& w =
6044 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006046
6047 touch();
6048
6049 mTouchWindow->consumeAnyMotionDown();
6050}
6051
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006052TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6053 const sp<FakeWindowHandle>& w =
6054 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6056
6057 touch();
6058
6059 w->assertNoEvents();
6060}
6061
6062/**
6063 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6064 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6065 * window, the occluding window will still receive ACTION_OUTSIDE event.
6066 */
6067TEST_F(InputDispatcherUntrustedTouchesTest,
6068 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6069 const sp<FakeWindowHandle>& w =
6070 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006071 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6073
6074 touch();
6075
6076 w->consumeMotionOutside();
6077}
6078
6079TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6080 const sp<FakeWindowHandle>& w =
6081 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006082 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6084
6085 touch();
6086
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006087 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006088}
6089
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006090TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006091 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006092 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6093 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6095
6096 touch();
6097
6098 mTouchWindow->consumeAnyMotionDown();
6099}
6100
6101TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6102 const sp<FakeWindowHandle>& w =
6103 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6104 MAXIMUM_OBSCURING_OPACITY);
6105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006106
6107 touch();
6108
6109 mTouchWindow->consumeAnyMotionDown();
6110}
6111
6112TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006113 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006114 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6115 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6117
6118 touch();
6119
6120 mTouchWindow->assertNoEvents();
6121}
6122
6123TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6124 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6125 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006126 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6127 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006128 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006129 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6130 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6132
6133 touch();
6134
6135 mTouchWindow->assertNoEvents();
6136}
6137
6138TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6139 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6140 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006141 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6142 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006143 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006144 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6145 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6147
6148 touch();
6149
6150 mTouchWindow->consumeAnyMotionDown();
6151}
6152
6153TEST_F(InputDispatcherUntrustedTouchesTest,
6154 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6155 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006156 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6157 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006158 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006159 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6160 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6162
6163 touch();
6164
6165 mTouchWindow->consumeAnyMotionDown();
6166}
6167
6168TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6169 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006170 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6171 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006172 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006173 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6174 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006176
6177 touch();
6178
6179 mTouchWindow->assertNoEvents();
6180}
6181
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006182TEST_F(InputDispatcherUntrustedTouchesTest,
6183 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6184 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006185 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6186 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006187 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006188 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6189 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6191
6192 touch();
6193
6194 mTouchWindow->assertNoEvents();
6195}
6196
6197TEST_F(InputDispatcherUntrustedTouchesTest,
6198 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6199 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006200 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6201 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006202 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006203 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6204 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6206
6207 touch();
6208
6209 mTouchWindow->consumeAnyMotionDown();
6210}
6211
6212TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6213 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006214 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6215 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6217
6218 touch();
6219
6220 mTouchWindow->consumeAnyMotionDown();
6221}
6222
6223TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6224 const sp<FakeWindowHandle>& w =
6225 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6227
6228 touch();
6229
6230 mTouchWindow->consumeAnyMotionDown();
6231}
6232
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006233TEST_F(InputDispatcherUntrustedTouchesTest,
6234 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6235 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6236 const sp<FakeWindowHandle>& w =
6237 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6239
6240 touch();
6241
6242 mTouchWindow->assertNoEvents();
6243}
6244
6245TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6246 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6247 const sp<FakeWindowHandle>& w =
6248 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6250
6251 touch();
6252
6253 mTouchWindow->consumeAnyMotionDown();
6254}
6255
6256TEST_F(InputDispatcherUntrustedTouchesTest,
6257 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6258 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6259 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006260 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6261 OPACITY_ABOVE_THRESHOLD);
6262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6263
6264 touch();
6265
6266 mTouchWindow->consumeAnyMotionDown();
6267}
6268
6269TEST_F(InputDispatcherUntrustedTouchesTest,
6270 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6271 const sp<FakeWindowHandle>& w1 =
6272 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6273 OPACITY_BELOW_THRESHOLD);
6274 const sp<FakeWindowHandle>& w2 =
6275 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6276 OPACITY_BELOW_THRESHOLD);
6277 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6278
6279 touch();
6280
6281 mTouchWindow->assertNoEvents();
6282}
6283
6284/**
6285 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6286 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6287 * (which alone would result in allowing touches) does not affect the blocking behavior.
6288 */
6289TEST_F(InputDispatcherUntrustedTouchesTest,
6290 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6291 const sp<FakeWindowHandle>& wB =
6292 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6293 OPACITY_BELOW_THRESHOLD);
6294 const sp<FakeWindowHandle>& wC =
6295 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6296 OPACITY_BELOW_THRESHOLD);
6297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6298
6299 touch();
6300
6301 mTouchWindow->assertNoEvents();
6302}
6303
6304/**
6305 * This test is testing that a window from a different UID but with same application token doesn't
6306 * block the touch. Apps can share the application token for close UI collaboration for example.
6307 */
6308TEST_F(InputDispatcherUntrustedTouchesTest,
6309 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6310 const sp<FakeWindowHandle>& w =
6311 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6312 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6314
6315 touch();
6316
6317 mTouchWindow->consumeAnyMotionDown();
6318}
6319
arthurhungb89ccb02020-12-30 16:19:01 +08006320class InputDispatcherDragTests : public InputDispatcherTest {
6321protected:
6322 std::shared_ptr<FakeApplicationHandle> mApp;
6323 sp<FakeWindowHandle> mWindow;
6324 sp<FakeWindowHandle> mSecondWindow;
6325 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006326 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006327 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6328 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006329
6330 void SetUp() override {
6331 InputDispatcherTest::SetUp();
6332 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006333 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006334 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006335
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006336 mSecondWindow =
6337 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006338 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006339
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006340 mSpyWindow =
6341 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006342 mSpyWindow->setSpy(true);
6343 mSpyWindow->setTrustedOverlay(true);
6344 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6345
arthurhungb89ccb02020-12-30 16:19:01 +08006346 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006348 }
6349
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006350 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6351 switch (fromSource) {
6352 case AINPUT_SOURCE_TOUCHSCREEN:
6353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6354 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6355 ADISPLAY_ID_DEFAULT, {50, 50}))
6356 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6357 break;
6358 case AINPUT_SOURCE_STYLUS:
6359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6360 injectMotionEvent(
6361 mDispatcher,
6362 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6363 AINPUT_SOURCE_STYLUS)
6364 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6365 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6366 .x(50)
6367 .y(50))
6368 .build()));
6369 break;
6370 case AINPUT_SOURCE_MOUSE:
6371 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6372 injectMotionEvent(
6373 mDispatcher,
6374 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6375 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6376 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6377 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6378 .x(50)
6379 .y(50))
6380 .build()));
6381 break;
6382 default:
6383 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6384 }
arthurhungb89ccb02020-12-30 16:19:01 +08006385
6386 // Window should receive motion event.
6387 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006388 // Spy window should also receive motion event
6389 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006390 }
6391
6392 // Start performing drag, we will create a drag window and transfer touch to it.
6393 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6394 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006395 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006396 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006397 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006398 }
arthurhungb89ccb02020-12-30 16:19:01 +08006399
6400 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006401 mDragWindow =
6402 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006403 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006404 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006405 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006406
6407 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006408 bool transferred =
6409 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6410 true /* isDragDrop */);
6411 if (transferred) {
6412 mWindow->consumeMotionCancel();
6413 mDragWindow->consumeMotionDown();
6414 }
6415 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006416 }
6417};
6418
6419TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006420 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006421
6422 // Move on window.
6423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6424 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6425 ADISPLAY_ID_DEFAULT, {50, 50}))
6426 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6427 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6428 mWindow->consumeDragEvent(false, 50, 50);
6429 mSecondWindow->assertNoEvents();
6430
6431 // Move to another window.
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6434 ADISPLAY_ID_DEFAULT, {150, 50}))
6435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6436 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6437 mWindow->consumeDragEvent(true, 150, 50);
6438 mSecondWindow->consumeDragEvent(false, 50, 50);
6439
6440 // Move back to original window.
6441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6442 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6443 ADISPLAY_ID_DEFAULT, {50, 50}))
6444 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6445 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6446 mWindow->consumeDragEvent(false, 50, 50);
6447 mSecondWindow->consumeDragEvent(true, -50, 50);
6448
6449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6450 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6451 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6452 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6453 mWindow->assertNoEvents();
6454 mSecondWindow->assertNoEvents();
6455}
6456
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006457TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006458 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006459
6460 // No cancel event after drag start
6461 mSpyWindow->assertNoEvents();
6462
6463 const MotionEvent secondFingerDownEvent =
6464 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6465 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6466 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6467 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6468 .build();
6469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6470 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6471 InputEventInjectionSync::WAIT_FOR_RESULT))
6472 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6473
6474 // Receives cancel for first pointer after next pointer down
6475 mSpyWindow->consumeMotionCancel();
6476 mSpyWindow->consumeMotionDown();
6477
6478 mSpyWindow->assertNoEvents();
6479}
6480
arthurhungf452d0b2021-01-06 00:19:52 +08006481TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006482 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006483
6484 // Move on window.
6485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6486 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6487 ADISPLAY_ID_DEFAULT, {50, 50}))
6488 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6489 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6490 mWindow->consumeDragEvent(false, 50, 50);
6491 mSecondWindow->assertNoEvents();
6492
6493 // Move to another window.
6494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6495 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6496 ADISPLAY_ID_DEFAULT, {150, 50}))
6497 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6498 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6499 mWindow->consumeDragEvent(true, 150, 50);
6500 mSecondWindow->consumeDragEvent(false, 50, 50);
6501
6502 // drop to another window.
6503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6504 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6505 {150, 50}))
6506 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6507 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6508 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6509 mWindow->assertNoEvents();
6510 mSecondWindow->assertNoEvents();
6511}
6512
arthurhung6d4bed92021-03-17 11:59:33 +08006513TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006514 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006515
6516 // Move on window and keep button pressed.
6517 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6518 injectMotionEvent(mDispatcher,
6519 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6520 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6521 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6522 .x(50)
6523 .y(50))
6524 .build()))
6525 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6526 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6527 mWindow->consumeDragEvent(false, 50, 50);
6528 mSecondWindow->assertNoEvents();
6529
6530 // Move to another window and release button, expect to drop item.
6531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6532 injectMotionEvent(mDispatcher,
6533 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6534 .buttonState(0)
6535 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6536 .x(150)
6537 .y(50))
6538 .build()))
6539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6540 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6541 mWindow->assertNoEvents();
6542 mSecondWindow->assertNoEvents();
6543 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6544
6545 // nothing to the window.
6546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6547 injectMotionEvent(mDispatcher,
6548 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6549 .buttonState(0)
6550 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6551 .x(150)
6552 .y(50))
6553 .build()))
6554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6555 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6556 mWindow->assertNoEvents();
6557 mSecondWindow->assertNoEvents();
6558}
6559
Arthur Hung54745652022-04-20 07:17:41 +00006560TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006561 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006562
6563 // Set second window invisible.
6564 mSecondWindow->setVisible(false);
6565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6566
6567 // Move on window.
6568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6569 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6570 ADISPLAY_ID_DEFAULT, {50, 50}))
6571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6572 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6573 mWindow->consumeDragEvent(false, 50, 50);
6574 mSecondWindow->assertNoEvents();
6575
6576 // Move to another window.
6577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6578 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6579 ADISPLAY_ID_DEFAULT, {150, 50}))
6580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6581 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6582 mWindow->consumeDragEvent(true, 150, 50);
6583 mSecondWindow->assertNoEvents();
6584
6585 // drop to another window.
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6588 {150, 50}))
6589 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6590 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6591 mFakePolicy->assertDropTargetEquals(nullptr);
6592 mWindow->assertNoEvents();
6593 mSecondWindow->assertNoEvents();
6594}
6595
Arthur Hung54745652022-04-20 07:17:41 +00006596TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006597 // Ensure window could track pointerIds if it didn't support split touch.
6598 mWindow->setPreventSplitting(true);
6599
Arthur Hung54745652022-04-20 07:17:41 +00006600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6602 {50, 50}))
6603 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6604 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6605
6606 const MotionEvent secondFingerDownEvent =
6607 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6608 .displayId(ADISPLAY_ID_DEFAULT)
6609 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6610 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6611 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6612 .build();
6613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6614 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6615 InputEventInjectionSync::WAIT_FOR_RESULT))
6616 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6617 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6618
6619 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006620 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006621}
6622
6623TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6624 // First down on second window.
6625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6626 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6627 {150, 50}))
6628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6629
6630 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6631
6632 // Second down on first window.
6633 const MotionEvent secondFingerDownEvent =
6634 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6635 .displayId(ADISPLAY_ID_DEFAULT)
6636 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6637 .pointer(
6638 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6639 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6640 .build();
6641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6642 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6643 InputEventInjectionSync::WAIT_FOR_RESULT))
6644 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6645 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6646
6647 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006648 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006649
6650 // Move on window.
6651 const MotionEvent secondFingerMoveEvent =
6652 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6653 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6654 .pointer(
6655 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6656 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6657 .build();
6658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6659 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6660 InputEventInjectionSync::WAIT_FOR_RESULT));
6661 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6662 mWindow->consumeDragEvent(false, 50, 50);
6663 mSecondWindow->consumeMotionMove();
6664
6665 // Release the drag pointer should perform drop.
6666 const MotionEvent secondFingerUpEvent =
6667 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6668 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6669 .pointer(
6670 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6671 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6672 .build();
6673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6674 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6675 InputEventInjectionSync::WAIT_FOR_RESULT));
6676 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6677 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6678 mWindow->assertNoEvents();
6679 mSecondWindow->consumeMotionMove();
6680}
6681
Arthur Hung3915c1f2022-05-31 07:17:17 +00006682TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006683 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006684
6685 // Update window of second display.
6686 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006687 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006688 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6689
6690 // Let second display has a touch state.
6691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6692 injectMotionEvent(mDispatcher,
6693 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6694 AINPUT_SOURCE_TOUCHSCREEN)
6695 .displayId(SECOND_DISPLAY_ID)
6696 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6697 .x(100)
6698 .y(100))
6699 .build()));
6700 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6701 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6702 // Update window again.
6703 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6704
6705 // Move on window.
6706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6707 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6708 ADISPLAY_ID_DEFAULT, {50, 50}))
6709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6710 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6711 mWindow->consumeDragEvent(false, 50, 50);
6712 mSecondWindow->assertNoEvents();
6713
6714 // Move to another window.
6715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6716 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6717 ADISPLAY_ID_DEFAULT, {150, 50}))
6718 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6719 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6720 mWindow->consumeDragEvent(true, 150, 50);
6721 mSecondWindow->consumeDragEvent(false, 50, 50);
6722
6723 // drop to another window.
6724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6725 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6726 {150, 50}))
6727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6728 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6729 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6730 mWindow->assertNoEvents();
6731 mSecondWindow->assertNoEvents();
6732}
6733
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006734TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6735 startDrag(true, AINPUT_SOURCE_MOUSE);
6736 // Move on window.
6737 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6738 injectMotionEvent(mDispatcher,
6739 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6740 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6741 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6742 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6743 .x(50)
6744 .y(50))
6745 .build()))
6746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6747 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6748 mWindow->consumeDragEvent(false, 50, 50);
6749 mSecondWindow->assertNoEvents();
6750
6751 // Move to another window.
6752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6753 injectMotionEvent(mDispatcher,
6754 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6755 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6756 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6757 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6758 .x(150)
6759 .y(50))
6760 .build()))
6761 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6762 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6763 mWindow->consumeDragEvent(true, 150, 50);
6764 mSecondWindow->consumeDragEvent(false, 50, 50);
6765
6766 // drop to another window.
6767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6768 injectMotionEvent(mDispatcher,
6769 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6770 .buttonState(0)
6771 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6772 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6773 .x(150)
6774 .y(50))
6775 .build()))
6776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6777 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6778 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6779 mWindow->assertNoEvents();
6780 mSecondWindow->assertNoEvents();
6781}
6782
Vishnu Nair062a8672021-09-03 16:07:44 -07006783class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6784
6785TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6786 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006787 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6788 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006789 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006790 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6791 window->setFocusable(true);
6792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6793 setFocusedWindow(window);
6794 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6795
6796 // With the flag set, window should not get any input
6797 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6798 mDispatcher->notifyKey(&keyArgs);
6799 window->assertNoEvents();
6800
6801 NotifyMotionArgs motionArgs =
6802 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6803 ADISPLAY_ID_DEFAULT);
6804 mDispatcher->notifyMotion(&motionArgs);
6805 window->assertNoEvents();
6806
6807 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006808 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6810
6811 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6812 mDispatcher->notifyKey(&keyArgs);
6813 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6814
6815 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6816 ADISPLAY_ID_DEFAULT);
6817 mDispatcher->notifyMotion(&motionArgs);
6818 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6819 window->assertNoEvents();
6820}
6821
6822TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6823 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6824 std::make_shared<FakeApplicationHandle>();
6825 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006826 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6827 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006828 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6829 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006830 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006832 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6833 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006834 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006835 window->setOwnerInfo(222, 222);
6836 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6837 window->setFocusable(true);
6838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6839 setFocusedWindow(window);
6840 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6841
6842 // With the flag set, window should not get any input
6843 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6844 mDispatcher->notifyKey(&keyArgs);
6845 window->assertNoEvents();
6846
6847 NotifyMotionArgs motionArgs =
6848 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6849 ADISPLAY_ID_DEFAULT);
6850 mDispatcher->notifyMotion(&motionArgs);
6851 window->assertNoEvents();
6852
6853 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006854 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6856
6857 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6858 mDispatcher->notifyKey(&keyArgs);
6859 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6860
6861 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6862 ADISPLAY_ID_DEFAULT);
6863 mDispatcher->notifyMotion(&motionArgs);
6864 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6865 window->assertNoEvents();
6866}
6867
6868TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6869 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6870 std::make_shared<FakeApplicationHandle>();
6871 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006872 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6873 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006874 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6875 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006876 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006877 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006878 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6879 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006880 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006881 window->setOwnerInfo(222, 222);
6882 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6883 window->setFocusable(true);
6884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6885 setFocusedWindow(window);
6886 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6887
6888 // With the flag set, window should not get any input
6889 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6890 mDispatcher->notifyKey(&keyArgs);
6891 window->assertNoEvents();
6892
6893 NotifyMotionArgs motionArgs =
6894 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6895 ADISPLAY_ID_DEFAULT);
6896 mDispatcher->notifyMotion(&motionArgs);
6897 window->assertNoEvents();
6898
6899 // When the window is no longer obscured because it went on top, it should get input
6900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6901
6902 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6903 mDispatcher->notifyKey(&keyArgs);
6904 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6905
6906 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6907 ADISPLAY_ID_DEFAULT);
6908 mDispatcher->notifyMotion(&motionArgs);
6909 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6910 window->assertNoEvents();
6911}
6912
Antonio Kantekf16f2832021-09-28 04:39:20 +00006913class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6914protected:
6915 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00006916 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006917 sp<FakeWindowHandle> mWindow;
6918 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00006919 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006920
6921 void SetUp() override {
6922 InputDispatcherTest::SetUp();
6923
6924 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00006925 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006926 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006927 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006928 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006929 mSecondWindow =
6930 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006931 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00006932 mThirdWindow =
6933 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
6934 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
6935 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006936
6937 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00006938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
6939 {SECOND_DISPLAY_ID, {mThirdWindow}}});
6940 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006941 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006942
Antonio Kantek15beb512022-06-13 22:35:41 +00006943 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006944 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00006945 WINDOW_UID, true /* hasPermission */,
6946 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006947 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6948 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006949 mThirdWindow->assertNoEvents();
6950 }
6951
6952 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
6953 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
6954 SECONDARY_WINDOW_UID, true /* hasPermission */,
6955 SECOND_DISPLAY_ID)) {
6956 mWindow->assertNoEvents();
6957 mSecondWindow->assertNoEvents();
6958 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07006959 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006960 }
6961
Antonio Kantek15beb512022-06-13 22:35:41 +00006962 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
6963 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006964 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6965 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006966 mWindow->consumeTouchModeEvent(inTouchMode);
6967 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006968 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00006969 }
6970};
6971
Antonio Kantek26defcf2022-02-08 01:12:27 +00006972TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006973 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00006974 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
6975 windowInfo.ownerPid, windowInfo.ownerUid,
6976 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006977}
6978
Antonio Kantek26defcf2022-02-08 01:12:27 +00006979TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6980 const WindowInfo& windowInfo = *mWindow->getInfo();
6981 int32_t ownerPid = windowInfo.ownerPid;
6982 int32_t ownerUid = windowInfo.ownerUid;
6983 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6984 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006985 ownerUid, false /*hasPermission*/,
6986 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006987 mWindow->assertNoEvents();
6988 mSecondWindow->assertNoEvents();
6989}
6990
6991TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6992 const WindowInfo& windowInfo = *mWindow->getInfo();
6993 int32_t ownerPid = windowInfo.ownerPid;
6994 int32_t ownerUid = windowInfo.ownerUid;
6995 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00006996 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
6997 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006998}
6999
Antonio Kantekf16f2832021-09-28 04:39:20 +00007000TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007001 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007002 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7003 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007004 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007005 mWindow->assertNoEvents();
7006 mSecondWindow->assertNoEvents();
7007}
7008
Antonio Kantek15beb512022-06-13 22:35:41 +00007009TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7010 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7011 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7012 windowInfo.ownerPid, windowInfo.ownerUid,
7013 true /*hasPermission*/, SECOND_DISPLAY_ID));
7014 mWindow->assertNoEvents();
7015 mSecondWindow->assertNoEvents();
7016 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7017}
7018
Antonio Kantek48710e42022-03-24 14:19:30 -07007019TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7020 // Interact with the window first.
7021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7022 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7023 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7024
7025 // Then remove focus.
7026 mWindow->setFocusable(false);
7027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7028
7029 // Assert that caller can switch touch mode by owning one of the last interacted window.
7030 const WindowInfo& windowInfo = *mWindow->getInfo();
7031 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7032 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007033 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007034}
7035
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007036class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7037public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007038 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007039 std::shared_ptr<FakeApplicationHandle> application =
7040 std::make_shared<FakeApplicationHandle>();
7041 std::string name = "Fake Spy ";
7042 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007043 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7044 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007045 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007046 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007047 return spy;
7048 }
7049
7050 sp<FakeWindowHandle> createForeground() {
7051 std::shared_ptr<FakeApplicationHandle> application =
7052 std::make_shared<FakeApplicationHandle>();
7053 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007054 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7055 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007056 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007057 return window;
7058 }
7059
7060private:
7061 int mSpyCount{0};
7062};
7063
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007064using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007065/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007066 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7067 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007068TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7069 ScopedSilentDeath _silentDeath;
7070
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007071 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007072 spy->setTrustedOverlay(false);
7073 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7074 ".* not a trusted overlay");
7075}
7076
7077/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007078 * Input injection into a display with a spy window but no foreground windows should succeed.
7079 */
7080TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007081 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7083
7084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7085 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7086 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7087 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7088}
7089
7090/**
7091 * Verify the order in which different input windows receive events. The touched foreground window
7092 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7093 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7094 * receive events before ones belows it.
7095 *
7096 * Here, we set up a scenario with four windows in the following Z order from the top:
7097 * spy1, spy2, window, spy3.
7098 * We then inject an event and verify that the foreground "window" receives it first, followed by
7099 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7100 * window.
7101 */
7102TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7103 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007104 auto spy1 = createSpy();
7105 auto spy2 = createSpy();
7106 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7108 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7109 const size_t numChannels = channels.size();
7110
Michael Wright8e9a8562022-02-09 13:44:29 +00007111 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007112 if (!epollFd.ok()) {
7113 FAIL() << "Failed to create epoll fd";
7114 }
7115
7116 for (size_t i = 0; i < numChannels; i++) {
7117 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7118 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7119 FAIL() << "Failed to add fd to epoll";
7120 }
7121 }
7122
7123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7124 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7126
7127 std::vector<size_t> eventOrder;
7128 std::vector<struct epoll_event> events(numChannels);
7129 for (;;) {
7130 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7131 (100ms).count());
7132 if (nFds < 0) {
7133 FAIL() << "Failed to call epoll_wait";
7134 }
7135 if (nFds == 0) {
7136 break; // epoll_wait timed out
7137 }
7138 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007139 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007140 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007141 channels[i]->consumeMotionDown();
7142 }
7143 }
7144
7145 // Verify the order in which the events were received.
7146 EXPECT_EQ(3u, eventOrder.size());
7147 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7148 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7149 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7150}
7151
7152/**
7153 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7154 */
7155TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7156 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007157 auto spy = createSpy();
7158 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7160
7161 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7162 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7163 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7164 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7165 spy->assertNoEvents();
7166}
7167
7168/**
7169 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7170 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7171 * to the window.
7172 */
7173TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7174 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007175 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007176 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7178
7179 // Inject an event outside the spy window's touchable region.
7180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7181 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7182 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7183 window->consumeMotionDown();
7184 spy->assertNoEvents();
7185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7186 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7187 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7188 window->consumeMotionUp();
7189 spy->assertNoEvents();
7190
7191 // Inject an event inside the spy window's touchable region.
7192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7193 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7194 {5, 10}))
7195 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7196 window->consumeMotionDown();
7197 spy->consumeMotionDown();
7198}
7199
7200/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007201 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007202 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007203 */
7204TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7205 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007206 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007207 auto spy = createSpy();
7208 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007209 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007210 spy->setFrame(Rect{0, 0, 20, 20});
7211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7212
7213 // Inject an event outside the spy window's frame and touchable region.
7214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007215 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7216 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007217 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7218 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007219 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007220}
7221
7222/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007223 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7224 * pointers that are down within its bounds.
7225 */
7226TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7227 auto windowLeft = createForeground();
7228 windowLeft->setFrame({0, 0, 100, 200});
7229 auto windowRight = createForeground();
7230 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007231 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007232 spy->setFrame({0, 0, 200, 200});
7233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7234
7235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7236 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7237 {50, 50}))
7238 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7239 windowLeft->consumeMotionDown();
7240 spy->consumeMotionDown();
7241
7242 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007243 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007244 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7245 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7246 .pointer(
7247 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7248 .build();
7249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7250 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7251 InputEventInjectionSync::WAIT_FOR_RESULT))
7252 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7253 windowRight->consumeMotionDown();
7254 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7255}
7256
7257/**
7258 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7259 * the spy should receive the second pointer with ACTION_DOWN.
7260 */
7261TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7262 auto window = createForeground();
7263 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007264 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007265 spyRight->setFrame({100, 0, 200, 200});
7266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7267
7268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7270 {50, 50}))
7271 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7272 window->consumeMotionDown();
7273 spyRight->assertNoEvents();
7274
7275 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007276 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007277 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7278 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7279 .pointer(
7280 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7281 .build();
7282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7283 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7284 InputEventInjectionSync::WAIT_FOR_RESULT))
7285 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7286 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7287 spyRight->consumeMotionDown();
7288}
7289
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007290/**
7291 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7292 * windows should be allowed to control split touch.
7293 */
7294TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007295 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007296 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007297 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007298 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007299
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007300 auto window = createForeground();
7301 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007302
7303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7304
7305 // First finger down, no window touched.
7306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7307 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7308 {100, 200}))
7309 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7310 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7311 window->assertNoEvents();
7312
7313 // Second finger down on window, the window should receive touch down.
7314 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007315 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007316 .displayId(ADISPLAY_ID_DEFAULT)
7317 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7318 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7319 .x(100)
7320 .y(200))
7321 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7322 .build();
7323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7324 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7325 InputEventInjectionSync::WAIT_FOR_RESULT))
7326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7327
7328 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7329 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7330}
7331
7332/**
7333 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7334 * do not receive key events.
7335 */
7336TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007337 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007338 spy->setFocusable(false);
7339
7340 auto window = createForeground();
7341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7342 setFocusedWindow(window);
7343 window->consumeFocusEvent(true);
7344
7345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7346 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7347 window->consumeKeyDown(ADISPLAY_ID_NONE);
7348
7349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7350 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7351 window->consumeKeyUp(ADISPLAY_ID_NONE);
7352
7353 spy->assertNoEvents();
7354}
7355
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007356using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7357
7358/**
7359 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7360 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7361 */
7362TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7363 auto window = createForeground();
7364 auto spy1 = createSpy();
7365 auto spy2 = createSpy();
7366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7367
7368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7369 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7370 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7371 window->consumeMotionDown();
7372 spy1->consumeMotionDown();
7373 spy2->consumeMotionDown();
7374
7375 // Pilfer pointers from the second spy window.
7376 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7377 spy2->assertNoEvents();
7378 spy1->consumeMotionCancel();
7379 window->consumeMotionCancel();
7380
7381 // The rest of the gesture should only be sent to the second spy window.
7382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7383 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7384 ADISPLAY_ID_DEFAULT))
7385 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7386 spy2->consumeMotionMove();
7387 spy1->assertNoEvents();
7388 window->assertNoEvents();
7389}
7390
7391/**
7392 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7393 * in the middle of the gesture.
7394 */
7395TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7396 auto window = createForeground();
7397 auto spy = createSpy();
7398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7399
7400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7403 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7404 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7405
7406 window->releaseChannel();
7407
7408 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7409
7410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7411 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7412 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7413 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7414}
7415
7416/**
7417 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7418 * the spy, but not to any other windows.
7419 */
7420TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7421 auto spy = createSpy();
7422 auto window = createForeground();
7423
7424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7425
7426 // First finger down on the window and the spy.
7427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7429 {100, 200}))
7430 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7431 spy->consumeMotionDown();
7432 window->consumeMotionDown();
7433
7434 // Spy window pilfers the pointers.
7435 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7436 window->consumeMotionCancel();
7437
7438 // Second finger down on the window and spy, but the window should not receive the pointer down.
7439 const MotionEvent secondFingerDownEvent =
7440 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7441 .displayId(ADISPLAY_ID_DEFAULT)
7442 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7443 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7444 .x(100)
7445 .y(200))
7446 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7447 .build();
7448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7449 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7450 InputEventInjectionSync::WAIT_FOR_RESULT))
7451 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7452
7453 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7454
7455 // Third finger goes down outside all windows, so injection should fail.
7456 const MotionEvent thirdFingerDownEvent =
7457 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7458 .displayId(ADISPLAY_ID_DEFAULT)
7459 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7460 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7461 .x(100)
7462 .y(200))
7463 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7464 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7465 .build();
7466 ASSERT_EQ(InputEventInjectionResult::FAILED,
7467 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7468 InputEventInjectionSync::WAIT_FOR_RESULT))
7469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7470
7471 spy->assertNoEvents();
7472 window->assertNoEvents();
7473}
7474
7475/**
7476 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7477 */
7478TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7479 auto spy = createSpy();
7480 spy->setFrame(Rect(0, 0, 100, 100));
7481 auto window = createForeground();
7482 window->setFrame(Rect(0, 0, 200, 200));
7483
7484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7485
7486 // First finger down on the window only
7487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7489 {150, 150}))
7490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7491 window->consumeMotionDown();
7492
7493 // Second finger down on the spy and window
7494 const MotionEvent secondFingerDownEvent =
7495 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7496 .displayId(ADISPLAY_ID_DEFAULT)
7497 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7498 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7499 .x(150)
7500 .y(150))
7501 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7502 .build();
7503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7504 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7505 InputEventInjectionSync::WAIT_FOR_RESULT))
7506 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7507 spy->consumeMotionDown();
7508 window->consumeMotionPointerDown(1);
7509
7510 // Third finger down on the spy and window
7511 const MotionEvent thirdFingerDownEvent =
7512 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7513 .displayId(ADISPLAY_ID_DEFAULT)
7514 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7515 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7516 .x(150)
7517 .y(150))
7518 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7519 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7520 .build();
7521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7522 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7523 InputEventInjectionSync::WAIT_FOR_RESULT))
7524 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7525 spy->consumeMotionPointerDown(1);
7526 window->consumeMotionPointerDown(2);
7527
7528 // Spy window pilfers the pointers.
7529 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7530 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7531 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7532
7533 spy->assertNoEvents();
7534 window->assertNoEvents();
7535}
7536
7537/**
7538 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7539 * other windows should be canceled. If this results in the cancellation of all pointers for some
7540 * window, then that window should receive ACTION_CANCEL.
7541 */
7542TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7543 auto spy = createSpy();
7544 spy->setFrame(Rect(0, 0, 100, 100));
7545 auto window = createForeground();
7546 window->setFrame(Rect(0, 0, 200, 200));
7547
7548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7549
7550 // First finger down on both spy and window
7551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7552 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7553 {10, 10}))
7554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7555 window->consumeMotionDown();
7556 spy->consumeMotionDown();
7557
7558 // Second finger down on the spy and window
7559 const MotionEvent secondFingerDownEvent =
7560 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7561 .displayId(ADISPLAY_ID_DEFAULT)
7562 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7563 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7564 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7565 .build();
7566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7567 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7568 InputEventInjectionSync::WAIT_FOR_RESULT))
7569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7570 spy->consumeMotionPointerDown(1);
7571 window->consumeMotionPointerDown(1);
7572
7573 // Spy window pilfers the pointers.
7574 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7575 window->consumeMotionCancel();
7576
7577 spy->assertNoEvents();
7578 window->assertNoEvents();
7579}
7580
7581/**
7582 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7583 * be sent to other windows
7584 */
7585TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7586 auto spy = createSpy();
7587 spy->setFrame(Rect(0, 0, 100, 100));
7588 auto window = createForeground();
7589 window->setFrame(Rect(0, 0, 200, 200));
7590
7591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7592
7593 // First finger down on both window and spy
7594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7596 {10, 10}))
7597 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7598 window->consumeMotionDown();
7599 spy->consumeMotionDown();
7600
7601 // Spy window pilfers the pointers.
7602 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7603 window->consumeMotionCancel();
7604
7605 // Second finger down on the window only
7606 const MotionEvent secondFingerDownEvent =
7607 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7608 .displayId(ADISPLAY_ID_DEFAULT)
7609 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7610 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7611 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7612 .x(150)
7613 .y(150))
7614 .build();
7615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7616 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7617 InputEventInjectionSync::WAIT_FOR_RESULT))
7618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7619 window->consumeMotionDown();
7620 window->assertNoEvents();
7621
7622 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7623 spy->consumeMotionMove();
7624 spy->assertNoEvents();
7625}
7626
Prabir Pradhand65552b2021-10-07 11:23:50 -07007627class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7628public:
7629 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7630 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7631 std::make_shared<FakeApplicationHandle>();
7632 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007633 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7634 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007635 overlay->setFocusable(false);
7636 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007637 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007638 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007639 overlay->setTrustedOverlay(true);
7640
7641 std::shared_ptr<FakeApplicationHandle> application =
7642 std::make_shared<FakeApplicationHandle>();
7643 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007644 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7645 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007646 window->setFocusable(true);
7647 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007648
7649 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7651 setFocusedWindow(window);
7652 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7653 return {std::move(overlay), std::move(window)};
7654 }
7655
7656 void sendFingerEvent(int32_t action) {
7657 NotifyMotionArgs motionArgs =
7658 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7659 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7660 mDispatcher->notifyMotion(&motionArgs);
7661 }
7662
7663 void sendStylusEvent(int32_t action) {
7664 NotifyMotionArgs motionArgs =
7665 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7666 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7667 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7668 mDispatcher->notifyMotion(&motionArgs);
7669 }
7670};
7671
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007672using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7673
7674TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7675 ScopedSilentDeath _silentDeath;
7676
Prabir Pradhand65552b2021-10-07 11:23:50 -07007677 auto [overlay, window] = setupStylusOverlayScenario();
7678 overlay->setTrustedOverlay(false);
7679 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7680 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7681 ".* not a trusted overlay");
7682}
7683
7684TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7685 auto [overlay, window] = setupStylusOverlayScenario();
7686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7687
7688 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7689 overlay->consumeMotionDown();
7690 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7691 overlay->consumeMotionUp();
7692
7693 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7694 window->consumeMotionDown();
7695 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7696 window->consumeMotionUp();
7697
7698 overlay->assertNoEvents();
7699 window->assertNoEvents();
7700}
7701
7702TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7703 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007704 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7706
7707 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7708 overlay->consumeMotionDown();
7709 window->consumeMotionDown();
7710 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7711 overlay->consumeMotionUp();
7712 window->consumeMotionUp();
7713
7714 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7715 window->consumeMotionDown();
7716 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7717 window->consumeMotionUp();
7718
7719 overlay->assertNoEvents();
7720 window->assertNoEvents();
7721}
7722
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007723/**
7724 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7725 * The scenario is as follows:
7726 * - The stylus interceptor overlay is configured as a spy window.
7727 * - The stylus interceptor spy receives the start of a new stylus gesture.
7728 * - It pilfers pointers and then configures itself to no longer be a spy.
7729 * - The stylus interceptor continues to receive the rest of the gesture.
7730 */
7731TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7732 auto [overlay, window] = setupStylusOverlayScenario();
7733 overlay->setSpy(true);
7734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7735
7736 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7737 overlay->consumeMotionDown();
7738 window->consumeMotionDown();
7739
7740 // The interceptor pilfers the pointers.
7741 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7742 window->consumeMotionCancel();
7743
7744 // The interceptor configures itself so that it is no longer a spy.
7745 overlay->setSpy(false);
7746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7747
7748 // It continues to receive the rest of the stylus gesture.
7749 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7750 overlay->consumeMotionMove();
7751 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7752 overlay->consumeMotionUp();
7753
7754 window->assertNoEvents();
7755}
7756
Prabir Pradhan5735a322022-04-11 17:23:34 +00007757struct User {
7758 int32_t mPid;
7759 int32_t mUid;
7760 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7761 std::unique_ptr<InputDispatcher>& mDispatcher;
7762
7763 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7764 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7765
7766 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7767 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7768 ADISPLAY_ID_DEFAULT, {100, 200},
7769 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7770 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7771 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7772 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7773 }
7774
7775 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7776 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7777 InputEventInjectionSync::WAIT_FOR_RESULT,
7778 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7779 mPolicyFlags);
7780 }
7781
7782 sp<FakeWindowHandle> createWindow() const {
7783 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7784 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007785 sp<FakeWindowHandle> window =
7786 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7787 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007788 window->setOwnerInfo(mPid, mUid);
7789 return window;
7790 }
7791};
7792
7793using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7794
7795TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7796 auto owner = User(mDispatcher, 10, 11);
7797 auto window = owner.createWindow();
7798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7799
7800 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7801 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7802 window->consumeMotionDown();
7803
7804 setFocusedWindow(window);
7805 window->consumeFocusEvent(true);
7806
7807 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7808 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7809 window->consumeKeyDown(ADISPLAY_ID_NONE);
7810}
7811
7812TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7813 auto owner = User(mDispatcher, 10, 11);
7814 auto window = owner.createWindow();
7815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7816
7817 auto rando = User(mDispatcher, 20, 21);
7818 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7819 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7820
7821 setFocusedWindow(window);
7822 window->consumeFocusEvent(true);
7823
7824 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7825 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7826 window->assertNoEvents();
7827}
7828
7829TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7830 auto owner = User(mDispatcher, 10, 11);
7831 auto window = owner.createWindow();
7832 auto spy = owner.createWindow();
7833 spy->setSpy(true);
7834 spy->setTrustedOverlay(true);
7835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7836
7837 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7838 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7839 spy->consumeMotionDown();
7840 window->consumeMotionDown();
7841}
7842
7843TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7844 auto owner = User(mDispatcher, 10, 11);
7845 auto window = owner.createWindow();
7846
7847 auto rando = User(mDispatcher, 20, 21);
7848 auto randosSpy = rando.createWindow();
7849 randosSpy->setSpy(true);
7850 randosSpy->setTrustedOverlay(true);
7851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7852
7853 // The event is targeted at owner's window, so injection should succeed, but the spy should
7854 // not receive the event.
7855 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7856 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7857 randosSpy->assertNoEvents();
7858 window->consumeMotionDown();
7859}
7860
7861TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7862 auto owner = User(mDispatcher, 10, 11);
7863 auto window = owner.createWindow();
7864
7865 auto rando = User(mDispatcher, 20, 21);
7866 auto randosSpy = rando.createWindow();
7867 randosSpy->setSpy(true);
7868 randosSpy->setTrustedOverlay(true);
7869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7870
7871 // A user that has injection permission can inject into any window.
7872 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7873 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7874 ADISPLAY_ID_DEFAULT));
7875 randosSpy->consumeMotionDown();
7876 window->consumeMotionDown();
7877
7878 setFocusedWindow(randosSpy);
7879 randosSpy->consumeFocusEvent(true);
7880
7881 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7882 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7883 window->assertNoEvents();
7884}
7885
7886TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7887 auto owner = User(mDispatcher, 10, 11);
7888 auto window = owner.createWindow();
7889
7890 auto rando = User(mDispatcher, 20, 21);
7891 auto randosWindow = rando.createWindow();
7892 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7893 randosWindow->setWatchOutsideTouch(true);
7894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7895
7896 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7897 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7898 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7899 window->consumeMotionDown();
7900 randosWindow->consumeMotionOutside();
7901}
7902
Garfield Tane84e6f92019-08-29 17:28:41 -07007903} // namespace android::inputdispatcher